Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript numberpad keycode parsing

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?

like image 871
Lee Quarella Avatar asked Feb 19 '12 15:02

Lee Quarella


2 Answers

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.

like image 117
Tim Down Avatar answered Sep 19 '22 20:09

Tim Down


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">
like image 26
T.J. Crowder Avatar answered Sep 20 '22 20:09

T.J. Crowder