Categories
JavaScript Answers

How to prevent typing non-numeric characters in input type number with JavaScript?

Spread the love

Sometimes, we want to prevent typing non-numeric characters in input type number with JavaScript.

In this article, we’ll look at how to prevent typing non-numeric characters in input type number with JavaScript.

How to prevent typing non-numeric characters in input type number with JavaScript?

To prevent typing non-numeric characters in input type number with JavaScript, we can listen for keypress events.

For instance, we write

document.querySelector("input").addEventListener("keypress", (evt) => {
  if (evt.which < 48 || evt.which > 57) {
    evt.preventDefault();
  }
});

to select the input with querySelector.

Then we call addEventListener to listen to the keypress event.

In the event handler, we check if non-numeric keys are pressed with evt.which < 48 || evt.which > 57.

If it’s true, then we call preventDefault to stop the character from being appended into the value.

Conclusion

To prevent typing non-numeric characters in input type number with JavaScript, we can listen for keypress events.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *