对于<input type="number">元素,maxlength无效。如何限制该数字元素的最大长度?


当前回答

更相关的属性是min和max。

其他回答

我以前遇到过这个问题,我使用html5数字类型和jQuery的组合解决了它。

<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>

脚本:

$("input[name='minutes']").on('keyup keypress blur change', function(e) {
    //return false if not 0-9
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       return false;
    }else{
        //limit length but allow backspace so that you can still delete the numbers.
        if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
            return false;
        }
    }
});

我不知道这些活动是否有点过分,但它解决了我的问题。 JSfiddle

梅考·莫拉的回答是一个好的开始。 然而,他的解决方案意味着当您输入第二个数字时,所有字段的编辑都会停止。因此,您不能更改值或删除任何字符。

下面的代码停在2,但允许继续编辑;

//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"

您可以指定min和max属性,这将只允许在特定范围内输入。

<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">

然而,这只适用于旋转控制按钮。尽管用户可以输入大于允许的最大值的数字,但表单将不会提交。

截图来自Chrome 15

你可以在JavaScript中使用HTML5的oninput事件来限制字符的数量:

myInput.oninput = function () {
    if (this.value.length > 4) {
        this.value = this.value.slice(0,4); 
    }
}

我使用一个简单的解决方案的所有输入(与jQuery):

$(document).on('input', ':input[type="number"][maxlength]', function () {
    if (this.value.length > this.maxLength) {
        this.value = this.value.slice(0, this.maxLength); 
    }
});

代码选择maxlength定义的所有输入类型="number"元素。

另一种选择是为任何具有maxlength属性的东西添加一个侦听器,并将切片值添加到其中。假设用户不想在与输入相关的每个事件中使用函数。下面是一个代码片段。忽略CSS和HTML代码,JavaScript才是最重要的。

// Reusable Function to Enforce MaxLength function enforce_maxlength(event) { var t = event.target; if (t.hasAttribute('maxlength')) { t.value = t.value.slice(0, t.getAttribute('maxlength')); } } // Global Listener for anything with an maxlength attribute. // I put the listener on the body, put it on whatever. document.body.addEventListener('input', enforce_maxlength); label { margin: 10px; font-size: 16px; display: block } input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px } span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 } <label for="test_input">Text Input</label> <input id="test_input" type="text" maxlength="5"/> <span>set to 5 maxlength</span> <br> <label for="test_input">Number Input</label> <input id="test_input" type="number" min="0" max="99" maxlength="2"/> <span>set to 2 maxlength, min 0 and max 99</span>