maxlength ignored for input type=“number” in Chrom

2019-01-03 08:39发布

The maxlength attribute is not working with <input type="number">. This happens only in Chrome.

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

15条回答
迷人小祖宗
2楼-- · 2019-01-03 09:13

Chrome (technically, Blink) will not implement maxlength for <input type="number">.

The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.

查看更多
老娘就宠你
3楼-- · 2019-01-03 09:13

The absolute solution that I've recently just tried is:

<input class="class-name" placeholder="1234567" name="elementname"  type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-03 09:15

Change your input type to text and use "oninput" event to call function:

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

Now use Javascript Regex to filter user input and limit it to numbers only:

function numberOnly(id) {
    // Get element by id which passed as parameter within HTML element event
    var element = document.getElementById(id);
    // Use numbers only pattern, from 0 to 9
    var regex = /[^0-9]/gi;
    // This removes any other character but numbers as entered by user
    element.value = element.value.replace(regex, "");
}

Demo: https://codepen.io/aslami/pen/GdPvRY

查看更多
女痞
5楼-- · 2019-01-03 09:16

I have two ways for you do that

First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:

<input type="tel" />

Second: Use a little bit of JavaScript:

<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />
查看更多
Root(大扎)
6楼-- · 2019-01-03 09:17

From MDN's documentation for <input>

If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.

So maxlength is ignored on <input type="number"> by design.

Depending on your needs, you can use the min and max attributes as inon suggested in his/her answer (NB: this will only define a constrained range, not the actual character length of the value, though -9999 to 9999 will cover all 0-4 digit numbers), or you can use a regular text input and enforce validation on the field with the new pattern attribute:

<input type="text" pattern="\d*" maxlength="4">
查看更多
beautiful°
7楼-- · 2019-01-03 09:17

You can try this as well for numeric input with length restriction

<input type="tel" maxlength="4" />
查看更多
登录 后发表回答