3 ms·
<input type="number"> is just completely awful. To handle it properly in our React application, we have a <NumberInput> component which is roughly 200 lines (an
by STRML 11y ago
<input type="number"> is just completely awful. To handle it properly in our React application, we have a <NumberInput> component which is roughly 200 lines (and shrinking, thankfully), involving more than a few browser-specific validity checks and keydown handlers.
The only way to keep non-numbers out of your number input is to cancel keydown events selectively, but it's still a crapshoot. And I've been bitten a few times by that bizarre change issue you mentioned.
If there's not already a good MIT-licensed project that encapsulates inputs and gets the weird out, I think it would be worth doing, whether in React or Web Components or both.
- Keats 11y agoAny plans on open sourcing yours?
- nmjenkins 11y ago> The only way to keep non-numbers out of your number input is to cancel keydown events selectively There's a much simpler way: monitor the "input" event, and whenever fired, do this.value = this.value.replace(/\D/g,''); The user will never see anything they type other than numbers.
- idbehold 11y agoI don't believe that will work since the input.value will become an empty string before you can do your replacement.
- eloisius 11y agoI think you would use a text input if you were writing your own component with better number behavior
- idbehold 11y agoYou'll trigger the wrong on-screen keyboard on mobile devices. There was talk about an inputmode attribute where you could specify "numeric" to instruct the OS to present the appropriate keyboard to the user without changing the input's behavior, but it isn't supported anywhere AFAIK.
- MatmaRex 11y agoThe user's cursor will also be moved to the end of the inputted text with every keystroke.
- sgrove 11y agoThis will blow away the cursor position: User enters: `1245|` Navigates back: `12|45` Enters 'a3': `12453|` Instead of: `12345` There are a ton of "gotchas" in this. Pretty frustrating.