簡體   English   中英

使用 JavaScript 或 jQuery 設置文本框的最大長度

[英]Setting maxlength of textbox with JavaScript or 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);
});

沒有 jQuery 你可以使用

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

設置屬性,而不是屬性

$("#ms_num").attr("maxlength", 6);
$('#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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM