Do not allow arrow keys to change values ​​in digital input

I have an input control on a web page similar to this:

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

If this control has focus, and I press the up or down arrow keys, the value in the text box is increasing or decreasing (except IE). I would like to disable this feature, preferably using CSS. I already have spinner buttons removed using CSS. I understand that I can use JavaScript to capture the keydown event, but I want the arrow keys to continue to scroll up or down the page.

+8
source share
5 answers

, CSS, CSS , .

, :

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

, , , JQuery, .

+11


HTML

<input type="number" min="1.01" max="1000" id="num"/>

CSS

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

JavaScript:

$(document).ready(function() {
$("input[type=number]").on("focus", function() {
    $(this).on("keydown", function(event) {
        if (event.keyCode === 38 || event.keyCode === 40) {
            event.preventDefault();
        }
     });
   });
});

: http://jsfiddle.net/649d66bb/

+1

<input type="number" name="value" onkeydown = 'return false'/>

, . , onkeypress onkeyup , false

0

, , , , ?

, , , , , - , .

- . , , Cmd/Ctrl + W . - , , .

Even with the standard margin, the type="text"up and down arrows do not scroll the page, this function seems to go against everything that is standard.

Saying that you did not give any context to this problem, and this could be for an internal tool or private use, in which case JS looks like a way!

-1
source

Oh, I was just able to do this with the keydown listener and the following filter:

const invalid = ['e', ',', '.', 'ArrowUp', 'ArrowDown'];
if (invalid.find(e => $event.key === e)) {
  $event.preventDefault();
}

In my case, I also want to ban characters: e , .

-3
source

Source: https://habr.com/ru/post/1544384/


All Articles