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


当前回答

与type="number"一样,指定max而不是maxlength属性,这是可能的最大数目。如果是4位数,最大值应该是9999,5位数是99999,以此类推。

另外,如果你想确保它是一个正数,你可以设置min="0",以确保它是正数。

其他回答

或者如果你的最大值是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">

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

您可以添加一个max属性,该属性将指定您可以插入的最大数字

<input type="number" max="999" />

如果你同时添加Max和min值,你可以指定允许值的范围:

<input type="number" min="1" max="999" />

以上仍然不会阻止用户手动输入指定范围之外的值。相反,他会看到一个弹出窗口,告诉他在提交表单时输入一个范围内的值,如下面的截图所示:

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

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

这对我来说没有任何问题

我使用一个简单的解决方案的所有输入(与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"元素。