使用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方法。另外,您的文档就绪功能在技术上也不正确:
$(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;
    }
});
    ,
<head>
    <script type=\"text/javascript\">
        function SetMaxLength () {
            var input = document.getElementById(\"myInput\");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id=\"myInput\" type=\"text\" size=\"20\" />
</body>
    ,
<head>
    <script type=\"text/javascript\">
        function SetMaxLength () {
            var input = document.getElementById (\"myInput\");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id=\"myInput\" type=\"text\" size=\"20\" />
</body>