When I press 8 from the numbers present above the alphabets on the keyboard, event.which returns 56, but when I press 8 from the numpad given at the side, it returns 104 (ascii of 'h'). I was doing this :

var keyPressed = event.which;
String.fromCharCode(keyPressed); // returns 8 from keyboard, 'h' from keypad

I am doing this inside the handler for the keydown event. Now, I know that each key on the keyboard has a different keyCode, and probably, event.which is returning the keyCode for the numpad 8, which just happens to coincide with the ascii 'h'. I simply want to have 8 returned irrespective of from where it has been typed.

Also, I can't bind the above code to the keyPress event handler as it doesn't capture delete, tab etc in IE.

2

There are 2 best solutions below

2
On

Ascii codes and character codes are two separate things. The numpad '8' results in a character code of 104, 'h' is 72. Every key has a different number, therefore h will always be 72.

Character Codes

There's a nice example in the Jquery Docs JQuery event.which

0
On

There is a better way to detect which key was pressed in JavaScript / jQuery.

First, on a general note, the keydown event is more effective at getting all the keys you want, as keypress won't necessarily fire on ENTER, ESC, TAB, arrow keys, etc.

To detect numbers from either the numeric keypad OR the line of numbers above the QWERTY keyboard, use:

event.keyIdentifier

or, with jQuery wrapped events:

event.originalEvent.keyIdentifier

"event" in these examples is the keydown event object.

This will give you a unicode string value representing the actual character of the key:

U+002F or U+0035, for example. Then, parse this unicode value as a hexidecimal number:

parseInt(event.keyIdentifier.substring(2),16)

Using 16 as the radix for parseInt will convert the hexidecimal number to a base-10.

With this method, all number keys will have the same value, whether they originate from the numberpad or the QWERTY keyboard. Numbers 0 - 9 are 48 - 57. So, an if() statement like this will find all numbers:

if (parseInt(event.keyIdentifier.substring(2),16) > 47 && parseInt(event.keyIdentifier.substring(2),16) < 58) {
    doSomething();
}