使用JavaScript或jQuery设置文本框的最大长度

我想用JavaScript或jQuery更改文本框的最大长度:我尝试了以下但它似乎没有帮助:

var a = document.getElementsByTagName('input'); for(var i=0; i<a.length; i++) { if((a[i].type!= 'radio')||(a[i].type!= 'checkbox')) a[i].maxlength = 5; } document.getElementsByTagName('input')[1].maxlength="3"; $().ready(function() { $("#inputID").maxlength(6); }); 

我究竟做错了什么?

不确定你在前几行尝试完成的是什么,但你可以试试这个:

 $(document).ready(function() { $("#ms_num").attr('maxlength','6'); }); 

最大长度属性是驼峰式的: maxLength

默认情况下,jQuery没有附带maxlength方法。 此外,您的文档就绪function在技术上不正确:

 $(document).ready(function () { $("#ms_num")[0].maxLength = 6; // OR: $("#ms_num").attr('maxlength', 6); // OR you can use prop if you are using jQuery 1.6+: $("#ms_num").prop('maxLength', 6); }); 

此外,由于您使用的是jQuery,您可以像这样重写代码(利用jQuery 1.6+):

 $('input').each(function (index) { var element = $(this); if (index === 1) { element.prop('maxLength', 3); } else if (element.is(':radio') || element.is(':checkbox')) { element.prop('maxLength', 5); } }); $(function() { $("#ms_num").prop('maxLength', 6); }); 

设置属性,而不是属性

 $("#ms_num").attr("maxlength", 6); 

没有jQuery你可以使用

 document.getElementById('text_input').setAttribute('maxlength',200); 
 $('#yourTextBoxId').live('change keyup paste', function(){ if ($('#yourTextBoxId').val().length > 11) { $('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10)); } }); 

我使用它和vars和选择器缓存性能,并做了伎俩..

你可以这样做:

 $('#inputID').keypress(function () { var maxLength = $(this).val().length; if (maxLength >= 5) { alert('You cannot enter more than ' + maxLength + ' chars'); return false; } }); 

maxlength="10"怎么样? 例如,