1

If I press left arrow event.KeyCode gives me 37.

If I press % symbol event.which gives me 37.

What to do in that situation, I only want to allow left arrow.

$('.cla').keypress(function(event) {
    var key = event.Which || event.keyCode
    if ((key >= 48 && key <= 57) || (key == 37)) {
        return true;
    } else return false;
});
nicael
  • 18,550
  • 13
  • 57
  • 90

2 Answers2

3

In order to press % you need to also press the shift key right ?

So if the shift key is pressed it should match the % symbol, the left arrow otherwise. You can check if the shift key is pressed with event.shiftKey

Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
1

keyPress does not include arrow keys - fiddle confirmation: https://jsfiddle.net/12a25f46/

keyPress event.which returns the ASCII character code that the key generates (eg Shift+A=65) - which makes no sense for arrow keys as they don't generate a character. So arrow keys are not included in keyPress.

keyUp / keyDown event.which shows the keyCode of the key pressed and will include arrows and whether shift(etc) was pressed.


So checking just keyPress will allow you to check for numbers and % and also allow the cursor to be moved via the arrow keys.

Separately checking for keyUp (or keyDown) will allow you to check any key, but it will not use the same numbers (eg % is 53+shift, not 37)

So there's no conflict.


Update: according to this question (which is somewhat similar...) this might be an issue in IE10. Fiddle above tested in chrome and IE11, not IE10.

Another valid answer the indicates keypress may be working incorrectly in some browsers.

Community
  • 1
  • 1
freedomn-m
  • 27,664
  • 8
  • 35
  • 57