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


当前回答

最大长度将不能与<input type="number"工作,我知道的最好的方法是使用oninput事件限制最大长度。请参阅下面的简单实现代码。

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />

其他回答

你可以将它指定为文本,但要添加只匹配数字的pettern:

<input type="text" pattern="\d*" maxlength="2">

它非常完美,而且在移动设备上(在iOS 8和Android上进行了测试),数字键盘也会弹出。

或者如果你的最大值是99,最小值是0,你可以把它加到输入元素中(你的值会被你的最大值重写)。

<input type="number" min="0" max="99" 
   onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">

然后(如果你想),你可以检查输入的是否真的数字

您可以指定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); 
    }
}

我以前遇到过这个问题,我使用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

更相关的属性是min和max。