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


当前回答

HTML输入

 <input class="minutesInput" type="number" min="10" max="120" value="" />

jQuery

 $(".minutesInput").on('keyup keypress blur change', function(e) {

    if($(this).val() > 120){
      $(this).val('120');
      return false;
    }

  });

其他回答

下面是使用maxlength的最简单的解决方案:

<form>
   <input class="form-control" id="code_pin" oninput="if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" maxlength="4">
</form>

这很简单,用一些javascript你可以模拟一个maxlength,看看:

//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />

我发现你不能使用任何onkeydown, onkeypress或onkeyup事件的完整解决方案,包括移动浏览器。顺便说一下,onkeypress已弃用,不再出现在chrome/opera的android(见:UI事件 W3C工作草案,2016年8月4日)。

我只使用oninput事件找到了一个解决方案。 你可能需要做额外的数字检查,如负号/正号或小数和千个分隔符等,但作为一个开始,以下应该足够了:

函数checkMaxLength(事件){ //准备恢复之前的值 如果这一点。oldValue === undefined) { 这一点。oldValue = this.defaultValue; } 如果(this.value。长度> this.maxLength) { //设置回前一个值 这一点。value = oldVal; } 其他{ //存储之前的值。 这一点。oldValue = this.value; //对+/-或。/等进行额外检查 //同时考虑合并'maxlength' //使用'min'和'max'来防止错误提交。 } }

我还建议将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

<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />

或者如果你想什么都不能输入

<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />