Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  192] [ 7]  / answers: 1 / hits: 11689  / 3 Years ago, thu, july 15, 2021, 12:00:00

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?


More From » html

 Answers
1

Try using inputmode attribute


https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode




<input inputmode=numeric oninput=this.value = this.value.replace(/D+/g, '')  />




References


https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode


[#1096] Friday, July 9, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keric

Total Points: 572
Total Questions: 93
Total Answers: 97

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
keric questions
;