开发者

Strict validation of text field

On my form there are two fields days and month.

I want to do simple validation for that. Once user enter the month , i.e., 12 then only it will be alllow to go to the next field.

If user enters invalid month then it should focus again on the month field and previously entered text should be selected.

I am trying to use .focus() and .select() jQ开发者_StackOverflow中文版uery function but its not working

This is fiction validation just to test , it can be any number or any label.

here is the jSFiddle link.

<input type="text" id="days" /> <input type="text" id="month" />

jQuery("#days").blur(function(){
    if(jQuery(this).val() == "12"){
        alert("valid");
    }
    else {
        alert("invalid");
        jQuery(this).focus().select();        
    } 
 });


$(function({
$('#days').attr("disabled", true);
});
$("#months").blur(function(){
    if($(this).val()<1 || $(this).val()>12){
       $(this).val() = "error, invalid month";
       $(this).css('color', 'red');
       $(this).focus();
       $('#days').attr("disabled", true);
       return;
    } 
else
{
 $('#days').attr("disabled", false);
}  
    }        
});


With this HTML

<label for="day">Day<input type="text" id="day" name="day"/></label>
<label for="month">Month<input type="text" id="month" name="month" maxlength=2/></label>

Use this JS

$('#day').live('keydown', function(e){
    keyCode = e.keyCode || e.which;
    if(keyCode == 9){
        if($(this).val()<1 || $(this).val()>32){
           e.preventDefault();
           $(this).trigger('select');
           console.log('error'); 
        }   
    }        
});
$('#month').live('keydown', function(e){
    keyCode = e.keyCode || e.which;
    if(keyCode == 9){
        if($(this).val()<1 || $(this).val()>12){
           e.preventDefault();
           $(this).trigger('select');
           console.log('error'); 
        }   
    }        
});

Link: http://jsfiddle.net/r6j7C/


Is it possible that the blur event goes through your code, and then finishes by focusing on whatever caused the blur? I can get the code to work if the code is changed from jQuery("#days").blur to jQuery("#month").focus.

jQuery("#month").focus(function(){
                if(jQuery(this).val() == "12"){
                        alert("valid");
                }
                        else
                {
                        alert("invalid");
                        jQuery("#days").focus();                      
                }
});


.focus() and .select() (for what you need them) are not jQuery functions, these are simple Javascript functions.

Well, actually they have a meaning in jQuery, they are used for event binding (for onfocus and onselect respectively).

You can simply call them by:

 this.focus();
 this.select();

if you need the "set focus on this element" and "select the contents of this element" functionality (which is pure JS, not jQuery).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜