Jquery - 限制文本输入中的文本,而不是textarea [英] Jquery - Limit text in text input, not textarea
问题描述
使用jquery如何限制可以在文本字段中输入的字符数?不是指textarea,只是一个普通的文本输入字段。我有一个表格,并通过iPad使用IOS5查看maxlength属性由于某种原因被忽略。如果我使用maxlength = 10,我可以在此字段中永久键入,它不会停止在10个字符。所以看起来我需要jquery来限制字段。有什么建议吗?
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?
更新
使用maxedison中的示例和来自的建议Marc B这是我想出的代码:
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);
}
});
推荐答案
您需要绑定到该字段的keydown事件如果该字段中已有10个字符,则阻止其输入字符: http://jsfiddle.net/j6tJ3/
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;
}
});
这篇关于Jquery - 限制文本输入中的文本,而不是textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!