Control of the keyboard with jquery to control numbers?

1
    if (event.shiftKey) 
        event.preventDefault();
}

if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
}
else {
    if (event.keyCode < 95) {
        if (event.keyCode < 48 || event.keyCode > 57) {
            event.preventDefault();
        }
    }
    else {
        if (event.keyCode < 96 || event.keyCode > 105) {
            event.preventDefault();
        }
    }
}

I have the following code to only accept numbers by keyboard, but I need to accept the tab key.

I read on the next page that the number equals 9 but it does not work for me

link

    
asked by Alcides Salazar 16.12.2016 в 04:02
source

2 answers

3

According to the MDN, the keyCode property is deprecated ; returns a numeric value dependent on the system and the implementation. You have no guarantee that the code is the same in all browsers or on all computers.

Instead, they recommend using the key property (a String):

  • If the key is printable , key contains the Unicode character.
  • If the key is control , key contains a name for that key. In particular, the tabulator is 'Tab' .

References

MDN - KeyboardEvent

MDN - KeyboardEvent.key

MDN - KeyboardEvent.key special values

    
answered by 16.12.2016 в 10:24
0

I have an approach that I think may be useful to you. It seems to me that your code is not working well because the Tab key has a default functionality, which is to "rotate" through the different elements, so if you normally press that key while in input , it will not work . One way to solve this is, in your function to handle that event, you can do the following:

function(e) {
    e.preventDefault();
    ...
    ...
}

That deactivates the predefined event for that or any other key and thus you will be able to handle well what you do. I hope it serves you.

    
answered by 18.12.2016 в 06:10