maxlength属性对<input type="number">不起作用。这只发生在Chrome。

<input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>

当前回答

我写了一个小而干净的解决方案。使用这个函数可以使它正常工作

  const inputHandler = (e) => {
    const { value, maxLength } = e.target;
    if (String(value).length >= maxLength) {
      e.preventDefault();
      return;
    }
  };

例如,它可以在React中这样使用:

<input
  type="number"
  maxlength="4"
  onKeyPress={inputHandler}
/>

其他回答

您可以使用min和max属性。

下面的代码做同样的事情:

<输入类型=“数字” 最小=“-999” 最大=“9999”/>

如何限制输入类型的最大长度

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

Chrome(技术上,Blink)将不会实现maxlength <input type="number">。

HTML5规范规定maxlength只适用于文本、url、电子邮件、搜索、电话和密码类型。

最大长度将不能与<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"
 />

根据Neha Jain上面的回答,我只是把下面的代码添加到公共区域

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

});

然后你可以像文本类型字段一样使用maxlength="4"。