对于<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;
    }

  });

其他回答

简单的解决方法,

输入滚动事件 通过键盘复制粘贴 通过鼠标复制粘贴 输入类型等情况 <输入id = " maxLengthCheck " name = " maxLengthCheck " type = "数量" 一步= " 1 " min = " 0 " oninput = "。Value = this。取值为> 5 ?5: Math.abs(this.value)"/>

这是有条件的。值> 5,只需更新5与您的最大限制。

解释:

如果我们的输入数大于我们的极限更新输入值this。Math.abs(this.value) 否则就达到最大限度,也就是5。

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

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

下面是使用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>

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

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;
    }

  });