How can I limit possible inputs in a HTML5 “number

2018-12-31 09:11发布

For <input type="number"> element, maxlength is not working. How can I restrict the maxlength for that number element?

22条回答
低头抚发
2楼-- · 2018-12-31 09:24

Ugh. It's like someone gave up half way through implementing it and thought no one would notice.

For whatever reason, the answers above don't use the min and max attributes. This jQuery finishes it up:

    $('input[type="number"]').on('input change keyup paste', function () {
      if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value));
      if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value));
    });

It would probably also work as a named function "oninput" w/o jQuery if your one of those "jQuery-is-the-devil" types.

查看更多
春风洒进眼中
3楼-- · 2018-12-31 09:25

As stated by others, min/max is not the same as maxlength because people could still enter a float that would be larger than the maximum string length that you intended. To truly emulate the maxlength attribute, you can do something like this in a pinch (this is equivalent to maxlength="16"):

<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">
查看更多
无与为乐者.
4楼-- · 2018-12-31 09:25

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

<input type="tel" maxlength="3" />
查看更多
心情的温度
5楼-- · 2018-12-31 09:29

Or if your max value is for example 99 and minimum 0, you can add this to input element (your value will be rewrited by your max value etc.)

<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">

Then (if you want), you could check if is input really number

查看更多
闭嘴吧你
6楼-- · 2018-12-31 09:29

More relevant attributes to use would be min and max.

查看更多
孤独寂梦人
7楼-- · 2018-12-31 09:30

For who's searching for a global limitation like me:

$(document).on('keypress','input[type="number"][maxlength]', function(){
    return this.value.length < +this.attributes.maxlength.value;
});

This catches every keypress on document, and filters it if the input is a "number" input and has a maxlength attribute. Then allows the pressed key when the length didn't reach the maxlength. It also works with dynamically added inputs and modals etc.

查看更多
登录 后发表回答