Reputation: 891
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;
}
});
});
Upvotes: 2
Views: 8982
Reputation: 724
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/
Upvotes: 0
Reputation: 148178
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) )
}
});
Upvotes: 7
Reputation: 6151
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
}
});
Upvotes: 2