Javascript numberpad keycode parsing

Lee Quarella picture Lee Quarella · Feb 19, 2012 · Viewed 10.1k times · Source

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?

Answer

Tim Down picture Tim Down · Feb 19, 2012

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.