Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

jQuery Snippet to Detect Keystrokes on the Numeric key-pad

0.00/5 (No votes)
11 Mar 2012CPOL1 min read 12.1K  
The below jQuery snippet returns the character corresponding to the key that was pressed on the QWERTY keyboard or the numeric key-pad.

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 ‘+’.

JavaScript
$(document).keydown(function (event) {
      toCharacter(event.keyCode);
 });

function toCharacter(keyCode) {

    // delta to convert num-pad key codes to QWERTY codes.
    var numPadToKeyPadDelta = 48;

    // if a numeric key on the num pad was pressed.
    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 "/";

    // the 'Enter' key was pressed
    if (keyCode == 13)
        return "=";  //TODO: you should change this to interpret the 'Enter' key as needed by your app.

    return String.fromCharCode(keyCode);
}

A Little Explanation is Probably In Order…

Javascript provides the...

JavaScript
String.fromCharCode()

...method that converts an ASCII character code into its equivalent text value. For instance:

JavaScript
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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)