Prevent arrow keys from changing values in a number input

Issue

I have an input control on a webpage similar to this:

<input type="number" name="value" />

If this control has focus and I hit either the up or down arrow keys, then the value in the textbox increments or decrements (except in IE).

I would like to disable this feature, preferably using CSS. I already have the spinner buttons removed using CSS. I realize I could use JavaScript to capture the keydown event, but I want to allow the arrow keys to continue to scroll the page up or down.

Solution

There is no way of doing the behavior you are describing purely with CSS because CSS handles display and we are talking about behavior and keyboard events here.

I would suggest to add an event listener to your input which will prevent the arrow keys from having an effect on it witout actually preventing the page scroll with the input is not in focus:

document.getElementById('yourInputID').addEventListener('keydown', function(e) {
    if (e.which === 38 || e.which === 40) {
        e.preventDefault();
    }
});

If by any chance you want the arrow keys to scroll the page event if the input is in focus, I would suggest using JQuery which will allow you to write less code and it will support all browsers.

Answered By – Ghassen Louhaichi

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.