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

50

我想使用JavaScript或jQuery更改文本框的maxlength值:我尝试了以下方法,但似乎没有起作用:

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);
});

我做错了什么?

9个回答

136

不确定你在前几行代码中尝试做什么,但你可以尝试这样:

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

1
这不是标准的写法,在IE7、8和9中无法正常工作,因此请避免使用它。 - Dynamic
1
@Dynamic 你有任何支持这个说法的链接或文档吗?根据w3SchoolsMozilla.Org这些仍然有效。请注意,在Mozilla文档中,它只适用于以下“<input>”标签类型:text、email、search、password、tel、url。 - Jay
8
这是正确的方式,Dynamic 是不正确的。这是一个标准属性。 - Angry 84
@Kamlesh 数字在长度方面与文本不同。请改用 minmax 属性。 - Jay

30

最大长度属性采用驼峰式命名: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);
});

1
看起来你和我同时回答了!! - Patricia
实际上,当我写下我的答案时,还没有其他帖子,但就在我发布我的答案后,Hunter的回复出现了。这是在快速回答和提供完整答案之间的微妙平衡。 - Jay

10

如果没有使用 jQuery,你可以使用以下方法:

document.getElementById('text_input').setAttribute('maxlength',200);

5

设置属性而不是属性

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

2
$('#yourTextBoxId').live('change keyup paste', function(){
    if ($('#yourTextBoxId').val().length > 11) {
        $('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10));
    }
});

我将此与变量和选择器缓存一起使用以提高性能,这样就行了。


1

对于像我一样遇到已接受答案问题的人:

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

您可以使用on focus代替ready函数:
$(document).on('focus', '#ms_num', function() {
{
    $(this).attr('maxlength','6');
});

当输入字段聚焦或被选中时,这将确保设置maxlength属性。


0
你可以这样做:
$('#inputID').keypress(function () {
    var maxLength = $(this).val().length;
    if (maxLength >= 5) {
        alert('You cannot enter more than ' + maxLength + ' chars');
        return false;
    }
});

0
<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>

因为问题是关于如何使用JS或JQ来实现的。;-) - KWallace

0
<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接