Reputation: 10146
Using jquery how can I limit the number of characters that can be typed in a text field? Not referring to a textarea, just a normal text input field. I have a form and viewing via an iPad using IOS5 the maxlength attribute for some reason is ignored. If I used maxlength=10 I can type forever in this field, it wont stop at 10 characters. So it looks like I will need jquery to limit the field. Any suggestions?
Update
Using the example from maxedison and the suggestion from Marc B this is the code I came up with that worked:
$('#textfld','#textform').keyup(function() {
if($(this).val().length > 20) {
var text = $(this).val().substring(0,20);
$(this).val(text);
}
});
Upvotes: 0
Views: 1415
Reputation: 17553
You need to bind to the keydown event for the field and prevent it from entering a character if there are already 10 in that field: http://jsfiddle.net/j6tJ3/
$('input').keydown(function(e){
if($(this).val().length > 9 && e.which !== 8 && e.which !== 46){ //if it's too long and the key pressed isn't backspace or delete
return false;
}
});
Upvotes: 4