You want to use <input type="number">
fields in your applications.
However, your desktop users may encounter some weird quirks:
to_i
in Ruby) you'll end up with wrong values (like 1 instead of 1000).inputmode="numeric"
).
We can fix all that with JavaScript:
const element = document.querySelector('#your-input')
// Number inputs allow incrementing/decrementing with arrow keys, and support exponential notation
// (in some browsers even regular letters). We want neither.
element.addEventListener('keydown', (event) => {
const key = event.key
const nonNumberKey = key.length === 1 && !event.ctrlKey && !event.altKey && !key.match(/[0-9\-+,.]/)
if (key === 'ArrowUp' || key === 'ArrowDown' || nonNumberKey) {
event.preventDefault()
}
})
// Some browser (at least Firefox) will increment/decrement a number when using the mouse's scroll wheel
// above a focused number input. Since this can lead to users changing values by accident, we want to avoid that.
element.addEventListener('wheel', (event) => {
if (element.matches(':focus')) {
event.preventDefault()
}
})
You can easily wrap this code your favorite frontend framework.
Additionally, you can hide the number field's up/down arrow buttons with CSS:
input[type="number"] {
-moz-appearance: textfield;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
See https://codepen.io/foobear/pen/dyzyBBX Show archive.org snapshot for a demo page.