jquery focus on mobile field till reaches max length

时间:2015-06-26 09:53:49

标签: jquery

I need to restrict the mobile number field, not loose its focus till it reaches the max length.

suppose, if i click on tab after entering some numbers, say for example, 3 numbers, It should not focus out.

I tried in the following way, but its working only the mobile number field is blank and also not able to enter any character in the field

jquery

$(document).on('keydown','.mobile-verified', function(e){               
        if($('.mobile-verified').val().length>9 && e.which==9){
          //working code
        }
        else{            
            $(this).focus();
            return false;
        }       
    });

template

<input name="mobilenum" 
 class="mobnum mobile-verified" 
 maxlength="10"  
 type="text">   

1 个答案:

答案 0 :(得分:1)

Prevent the default tabbing behaviour only if the length of your input value is less than the maxLength property:

$(document).on('keydown','.mobile-verified', function(e){
    if (e.which == 9 && $(this).val().length < this.maxLength) {
        e.preventDefault();
    }
});

JSFiddle