Sometimes, we want to allow numbers, backspace, delete, left and right arrow keys in an HTML input with JavaScript.
In this article, we’ll look at how to allow numbers, backspace, delete, left and right arrow keys in an HTML input with JavaScript.
How to allow numbers, backspace, delete, left and right arrow keys in an HTML input with JavaScript?
To allow numbers, backspace, delete, left and right arrow keys in an HTML input with JavaScript, we can add a keypress handler and check for the allowed keys inside.
For instance, we write:
<input>
to add an input.
Then we write:
const input = document.querySelector('input')
input.onkeypress = (e) => {
if (e.keyCode < 48 || e.keyCode > 57) {
e.preventDefault()
} else {
console.log(e.key)
}
}
to select the input with querySelector
.
Then we set input.onkyepress
to a function that checks if the key pressed is any other than numbers, backspace, delete, left and right arrow keys with e.keyCode < 48 || e.keyCode > 57
.
If this is true
, then we call e.preventDefault
to stop the keypress.
Otherwise, we log the key value with e.key
.
Conclusion
To allow numbers, backspace, delete, left and right arrow keys in an HTML input with JavaScript, we can add a keypress handler and check for the allowed keys inside.