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

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

当前回答

许多人张贴的onKeyDown()事件根本不工作,即你不能删除一旦你达到限制。因此,使用onKeyPress()而不是onKeyDown(),它工作得很好。

下面是工作代码:

用户将不允许输入超过4位数字 < br > <input type="number" pattern="/^-?\d+\.? "\d*$/" onKeyPress="if(this.value.length==4) return false;"/>

其他回答

这段代码对我来说运行得很好。

在type="number"的输入中,可以添加以下属性:

oninput="constrainUserInput(this.id)"

完整的输入是这样的:

<input type="number" class="test_css" maxlength="4" oninput="constrainUserInput(this.id)" id="flight_number" name="number"/>

注意:必须为这个方法分配输入和ID

然后你可以添加以下JavaScript到你的HTML,它基本上替换任何字符超过你的maxlength属性用一个空引号(本质上删除它们):

function constrainUserInput(id) {
  let input = document.getElementById(id);
  let value = input.value;
  if (value.length > input.maxLength) {
    input.value = value.substring(0, input.maxLength);
  }
}

根据我的经验,人们问为什么maxlength被忽略的大多数问题是因为允许用户输入超过“允许”的字符数量。

正如其他注释所述,type="number"输入没有maxlength属性,而是有min和max属性。

要让字段限制可以插入的字符数量,同时允许用户在提交表单之前意识到这一点(否则浏览器应该识别值> max),您必须(至少目前)向该字段添加一个侦听器。

这是我过去使用的一个解决方案:http://codepen.io/wuori/pen/LNyYBM

最大长度将不能与<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"
 />
<input type="number" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">

演示 - JSFIDDLE

试着用tel:

 maxlength="5" type="tel"