Home > Back-end >  Maxlength for input type number
Maxlength for input type number

Time:02-11

I have a number input field in HTML.

  <input type="number" value="0">

and I'd like for the user to not be able to type more than five characters into the textbox.

I've used the maxlength attribute before when the type is set to text, but that doesn't work with the number attribute. Is there a relatively simple solution (inline HTML is preferred) to overcome this and limit the number of characters?

Thanks.

CodePudding user response:

If you want a maximum of 5 digits in the number, you can use the largest 5 digit number and set that as the max attribute for the input:

<input type="number" max="99999" />

The above will only maximize the number to 99999, but will not disallow input of more than 5 characters. This can't be done with HTML alone.

It can, though, be done with JavaScript. For example:

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

All the code above does is, oninput, it checks the number of characters in the input, and if that is exceeding the number of characters specified in maxlength, it deletes the character.


Source: maxlength ignored for input type="number" in Chrome

  • Related