Categories
JavaScript Answers

How to not allow typing alphabetic characters in a number input with JavaScript?

Spread the love

Sometimes, we want to not allow typing alphabetic characters in a number input with JavaScript.

In this article, we’ll look at how to not allow typing alphabetic characters in a number input with JavaScript.

How to not allow typing alphabetic characters in a number input with JavaScript?

To not allow typing alphabetic characters in a number input with JavaScript, we can listen for the keypress event and check which key is pressed when the event is triggered.

For instance, we write:

<input>

to add an input.

Then we write:

const input = document.querySelector('input')
input.onkeypress = (evt) => {
  const charCode = evt.keyCode;
  if (charCode != 46 && charCode > 31 &&
    (charCode < 48 || charCode > 57)) {
    evt.preventDefault()
  }
}

to select an input with querySelector.

Then we add a keypress event handler on the input by setting the input.onkeypress property to a function that checks which key is pressed.

If a number key or a period isn’t pressed, then we call evt.preventDefault to stop the character for the key from being appended to the input value.

Conclusion

To not allow typing alphabetic characters in a number input with JavaScript, we can listen for the keypress event and check which key is pressed when the event is triggered.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.