12

I am attempting to parse keydown events from the numberpad with the following:

$('#myDiv').keydown(function(e) {
  val = String.fromCharCode(e.which)
});

The problem is that keypad 0-9 return keyCodes of 96-105 which, according to fromCharCode() are the lower case letters a-i. How do I get keydown events of the numberpad to resolve to the appropriate number?

Lee Quarella
  • 4,662
  • 5
  • 43
  • 68

5 Answers5

22

You don't: you use the keypress event. The keypress event is the only event that will give you reliable information about typed characters. Your existing code will work if you simply change keydown to keypress.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 1
    Suppose I both want real characters from the keypad, and also want to capture and stop the Enter key, to prevent a form submit? Stopping keypress appears to still submit. – enigment Aug 30 '12 at 20:49
  • I can't express how thankful I am for this answer. This was my salvation trying to catch all the different possible cases with shift, alt, numpad and mobile keyboards. `keypress` makes it easy as cake! – nirazul May 29 '13 at 15:45
9

The which value passed to keydown is not a character code; it's a key code (and the codes vary from browser/OS to browser/OS). You can map it to a character using the tables on this page, but to say that this stuff is a bit...awkward...would be to understate the case. :-)

Otherwise, your best bet is to wait for the keypress event, which will have the character code (if relevant) rather than a key code.

Example: Live copy | Live source

jQuery(function($) {

  $("#theField")
    .keydown(function(event) {
      showKey("keydown", event.which);
    })
    .keypress(function(event) {
      showKey("keypress", event.which);
    })
    .focus();

  function showKey(eventName, which) {
    display(eventName +
            ": " + which + " (" +
            String.fromCharCode(which) + ")");
  }

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

Using this HTML:

<input type="text" id="theField">
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

The answers here are now outdated because KeyboardEvent.which, KeyboardEvent.keyCode and KeyboardEvent.charCode are all deprecated.

The proper way for the latest versions of Firefox, Chrome, IE/Edge and Safari to obtain the character key is to use KeyboardEvent.key and it should work with any key event, not just keypress.

KeyboardEvent.key Browser Compatibility

document.
  querySelector('input').
  addEventListener('keydown', event => console.log(event.key));
<input placeholder="Start typing...">

If you still need to obtain the character code, you should use the KeyboardEvent.code property.

KeyboardEvent.code Browser Compatibility

document.
  querySelector('input').
  addEventListener('keydown', event => console.log(event.code));
<input placeholder="Start typing...">
nem035
  • 34,790
  • 6
  • 87
  • 99
1

There is a way to do this with keydown, if keypress is not workable due to event canceling needs, etc. Use an if() statement with this test:

parseInt(event.keyIdentifier.substring(2),16) > 47 && parseInt(event.keyIdentifier.substring(2),16) < 58

OR, with jQuery events:

parseInt(event.originalEvent.keyIdentifier.substring(2),16) > 47 && parseInt(event.originalEvent.keyIdentifier.substring(2),16) < 58

These examples assume "event" is the keydown event. keyIdentifier is a hexidecimal number that represents the unicode value for the related char. Using keyIdentifier, numbers from the numberpad / keypad AND the numbers above your QWERTY keyboard will all have the same values, 48 - 57 (U+0030 - U+0039), even with the keyDown event.

Unicode values in the browsers will look like U+0030 or U+002F. Parse this string to only get the hexidecimal value, then use parseInt() with a radix of 16 to convert it to base-10.

ChrisN
  • 302
  • 2
  • 9
0

you can use keydown and detect numpad keys. I did it using following code. Subtract 48 from numpad keys before interpreting the key

function navigate(e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode >= 96 && keyCode <= 105) {
            // Numpad keys
            keyCode -= 48;
        }  
        var txtVal = String.fromCharCode(keyCode);
Sacky San
  • 1,535
  • 21
  • 26