The below jQuery snippet returns the character corresponding to the key that was pressed on the QWERTY keyboard or the numeric key-pad. For instance, pressing the ’1' key will return the text ’1'. Similarly, pressing the ‘+’ key will return back the text ‘+’.
$(document).keydown(function (event) {
toCharacter(event.keyCode);
});
function toCharacter(keyCode) {
var numPadToKeyPadDelta = 48;
if (keyCode >= 96 && keyCode <= 105) {
keyCode = keyCode - numPadToKeyPadDelta;
return String.fromCharCode(keyCode);
}
if (keyCode == 106)
return "*";
if (keyCode == 107)
return "+";
if (keyCode == 109)
return "-";
if (keyCode == 110)
return ".";
if (keyCode == 111)
return "/";
if (keyCode == 13)
return "=";
return String.fromCharCode(keyCode);
}
A Little Explanation is Probably In Order…
Javascript provides the...
String.fromCharCode()
...method that converts an ASCII character code into its equivalent text value. For instance:
String.fromCharCode(65)
returns the character ‘A
’. The method works great until you try to use it for keys that live on the numeric keypad.
The ASCII code for the ’1' key on the numeric key pad is 97. If you look this up on the ASCII Table, you will find that the ASCII code 97 corresponds to the character ‘a’ and not the character ’1' denoted on the numeric key pad! The reason for this, as far I can tell, is that the numeric keys simply overload on the existing the ASCII codes.
A little calculation will reveal that subtracting 48 from the ASCII code of the numeric keys will give us the “correct” ASCII code. For instance, subtracting 97 (which is the ASCII code for the ’1' key on the numeric keypad) from 48 gives us 49. Look up the ASCII code 49 on the ASCII Table and you will find that it maps to the character ’1'!
For the keys that correspond to the various symbols such as ‘+’, ‘-’, etc., I am simply returning back the corresponding character. No mystery there.
Hope this helps!