How to input only numbers with <input type="text">.

How to input only numbers with <input type=”text”>.

If type=”number” is used in the input component, only numbers can be entered, but the maxlength attribute does not work in modern browsers.

To leave type=”text” as “number only”, you can use the pattern attribute to make it numeric only, but since this numeric check is done at the time of submit, you cannot use pattern to check when the input is submitted.

Using oninput

You can use oninput to check and resolve all input events.

In this case, since type=”text” is still used, maxlength can also be used.

Specifically, if a non-numeric input is entered using a regular expression, it will be replaced with an empty string, and only numeric input will be allowed.

<input type="text" maxlength="5" oninput="value = value.replace(/[^0-9]+/i,'');" />

Maxlength is enabled for input type=”number”.

If you want to display (increment or decrement) the number spinner button in modern browsers, you can use the max attribute to make it look like maxlength is in effect.

The following is an example of max=”99999″ with a maximum of 5 digits (maxlength=”5″); if the number entered from the keyboard during onkeyup is more than 5 digits, it is sliced.

<input type="number" onkeyup="value = value.length > 5 ? value.slice(0,5): value;" max="99999" />