Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent arrow keys from changing values in a number input

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.

like image 954
Rono Avatar asked Jun 12 '14 19:06

Rono


People also ask

How do I turn off input arrows in numbers?

Using inputmode=”numeric” attribute you can find an input box without an arrow.

How do I stop using arrow keys when coding?

For more fun, try: select a few words (ctrl+shift+Fn+arrows), then type over with something that starts with a capital letter or symbol (Shift+key, no Fn). I usually end up pressing Fn+key instead of Shift+key if I try to do this quickly.

How do I change the settings on my arrow keys?

Fortunately, on most keyboards, you can toggle between the standard-setting and the alternate key setting by pressing FN + W keys.

Can you disable arrow keys?

Scroll down to the bottom and select the 'Mouse' option under 'Interaction'. In the 'Mouse' settings, verify if the 'Mouse Keys' feature is disabled. In case it's turned on, click on the toggle to disable it.


2 Answers

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.

like image 57
Ghassen Louhaichi Avatar answered Sep 30 '22 12:09

Ghassen Louhaichi


You can use the below code (JSFiddle):

$(document).ready(function() {
  $("input[type=number]").on("focus", function() {
    $(this).on("keydown", function(event) {
      if (event.keyCode === 38 || event.keyCode === 40) {
        event.preventDefault();
      }
    });
  });
});
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" min="1.01" max="1000" id="num" />
like image 42
anjaneyulubatta505 Avatar answered Sep 30 '22 13:09

anjaneyulubatta505