2

How can I have an input that is limited to 4 numbers/digits, but if text is typed the character length is infinite?

Final working code:

    function isNumber (o) {
  return ! isNaN (o-0);
}

$("#txt").keyup(function(e){
    txtVal = $(this).val();  
     if(isNumber(txtVal) && txtVal.length>4)
     {
         $(this).val(txtVal.substring(0,4) )
           $(".error").html("4 Numbers Only").show();
      return false;
     }
});
});
0

3 Answers 3

7

Live Demo

HTML

 <input id="txt1" type="text" name="usrname" />​

JAVASCRIPT

function isNumber (o) {
  return ! isNaN (o-0);
}  

$("#txt1").keyup(function(e){
txtVal = $(this).val();  
 if(isNumber(txtVal) && txtVal.length>4)
 {
     $(this).val(txtVal.substring(0,4) )
 }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Elementary tip. But how does that answers the Q?
You'll get +1 from me if you re-read the question. (infinite text but only 4 digits.)
@Adil Good work Adil...check this to,if user enters like this aaa111111111 and clear all the characters? jsfiddle.net/C4Y99/3
Yes @Gopesh this is one of the scenarios that might come across. This could help us but depends on what we exactly want. jsfiddle.net/C4Y99/4
Thanks for compliment @Gopesh :)
2

You could check if the value is a numeric value and when there are more then 4 characters trigger the validation.

$("#yourField").change(function(e){
     if(isNaN($(this).val()) && $(this).val().length > 4)
     {
        //trigger validation
     }
});

Comments

0

HTML

<input type="text" class="numeric" />

JQUERY

$('.numeric').keypress(function(e) { 

var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}

}).on('paste',function(e){ e.preventDefault();});

Working Example

http://jsfiddle.net/nadeemmnn2007/C4Y99/52/

1 Comment

please check the demo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.