Categories
JavaScript Answers

How to prevent arrow keys from changing values in a number input with JavaScript?

Spread the love

Sometimes, we want to prevent arrow keys from changing values in a number input with JavaScript.

In this article, we’ll look at how to prevent arrow keys from changing values in a number input with JavaScript.

How to prevent arrow keys from changing values in a number input with JavaScript?

To prevent arrow keys from changing values in a number input with JavaScript, we can check if the arrow keys are pressed and call preventDefault is they are.

For instance, we write:

<input type='number'>

to add a number input.

Then we write:

const input = document.querySelector('input')
input.onkeydown = (e) => {
  if (e.which === 38 || e.which === 40) {
    e.preventDefault();
  }
}

to select the input with querySelector.

And we set input.onkeydown with a function that checks if the up and down arrow keys with e.which.

Then we call e.preventDefault to stop the arrow keys from changing the input value.

Conclusion

To prevent arrow keys from changing values in a number input with JavaScript, we can check if the arrow keys are pressed and call preventDefault is they are.

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 *