I want to make an Input-Field in which you can only write natural numbers. (Yes, I know this can be a bad practice, as the user doesn't get any feedback). If you type anything else than a digit, it should not appear in the input. I want to use plain JavaScript (no JQuery).
This is how I'd do it normally:
<input oninput="this.value = this.value.replace(/\D+/g, '')">
But I found out, that <input type="number">
is much preferred for mobile devices, as it doesn't show the whole keyboard, but just digits.
So my question is, how can I combine type="number"
with the filtering (and make it compatible with Cut/Copy/Paste)?
The value of the <input type="number">
-element is always an empty String if any non-number-character is entered. So my filtering method from above doesn't work. Is there any workaround?
If not, I'd have to listen for keydown, paste, cut, and possibly many more events. Which events would I have to consider, how would I implement it, and is there any easier way I have overlooked?
<input type="number" />
??? It is not clear what you cannot do with type="number" - a user cannot type anything other than numbers in that – Nonexistence