keyCode values for numeric keypad?
Asked Answered
O

14

92

Do the numbers on a numeric keypad have a different keycode than the numbers at the top of a keyboard?

Here is some JavaScript that is supposed to run on the keyup event, but only if the keycode is between 48 and 57. Here is the code:

$('#rollNum').keyup(function(e) {
    if(e.keyCode >= 48 && e.keyCode <= 57) { //0-9 only
        var max = 15;
        var textLen = $(this).val().length;
        var textLeft = max - textLen;
        . . . 

My problem is that this code only runs in response to the numbers entered at the top of the keyboard, but does not run in response to numbers entered from the numeric keypad.

I'm thinking the answer must be that the numeric keypad has different keyCode values, but how do I find out what those are?

Overdone answered 2/11, 2012 at 14:15 Comment(4)
You could just alert/log e.keyCode and give yourself the answer.Junina
Here is the guide for every key on the keyboard help.adobe.com/en_US/AS2LCR/Flash_10.0/…Tann
They (e.keyCode) are different for keyup and keydown because these events are related to the physical keys and those keys are different. If you use e.which from keypress, you'll get the same values for both keys.Fleur
Reference for all keycodes ( with demo ) : codeforeach.com/javascript/…Splint
B
184

The keycodes are different. Keypad 0-9 is Keycode 96 to 105

Your if statement should be:

if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) { 
  // 0-9 only
}

Here's a reference guide for keycodes


-- UPDATE --

This is an old answer and keyCode has been deprecated. There are now alternative methods to achieve this, such as using key:

if ((e.key >= 48 && e.key <= 57) || (e.key >= 96 && e.key <= 105)) { 
  // 0-9 only
}

Here's an output tester for event.key, thanks to @Danziger for the link.

Banas answered 2/11, 2012 at 14:17 Comment(7)
Wanted to note that this is different in jQuery's .keypress() event, which reports 48-57 for numbers whether they come from the keyboard or numpad.Chinchy
Reference for all keycodes ( with demo ) : codeforeach.com/javascript/…Splint
you should use KeyValue instead of keyCode in keyDown eventBustup
@Bustup 1) the logic here is using keyup, not keydown. 2) There is no keyValue property in a jQuery event.Banas
1+ here also key code blogs.longwin.com.tw/lifetype/key_codes.html and demo test here speedysense.com/javascript-keyboard-event keypress event.Paedo
e.keyCode is deprecated. e.key simplifies this a lot. Also, instead of using static charts to find the key codes/identifiers you need, you could check them out by just clicking the actual keys in here: keyjs.devBrannon
Don't use codes unless all your users have the same exact keyboard layout as yourself. Codes identify physical keys, not the character these keys are going to send. Prefer e.key which is much more portable. For numeric keypad, use e.location to distinguish which part of the keyboard it comes from.Carlyle
D
25

******************* Don't use KEYCODE !!!! ******************

The problem with keyCode is to avoid the combined keys with the numbers on top of keyboard, we must add a check on the key "Shift" and "Alt" to avoid special characters such as e @ & " { } ...

A simplest solution is to convert e.key to a number and check if the conversion gives NaN!

let key = Number(e.key)
if (isNaN(key) || e.key === null || e.key === ' ') {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}

Be careful if e.key is null or a space, it gives 0 !

Number(5)         // => 5
Number('5')       // => 5
Number(null)      // => 0 
Number(' ')       // => 0
Number('chars')   // => NaN
Number(undefined) // => NaN
Demodulator answered 9/1, 2018 at 15:6 Comment(3)
We can use parseInt except Number then it results NaN when it's space or null.Pavonine
One more thing we might beware of keyboard language layout. Some keyboard layouts changed default numeric keys to symbols.Pavonine
Good job @AlmasDusal. Test can also become if ( parseInt(e.key) >= 0 ) ...Eckard
K
9

You can simply run

$(document).keyup(function(e) {
    console.log(e.keyCode);
});

to see the codes of pressed keys in the browser console.

Or you can find key codes here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#Numpad_keys

Kamasutra answered 2/11, 2012 at 14:23 Comment(1)
This answer may not be useful if you're using a keyboard without a numeric keypadRuelu
S
6

keyCode is different for numbers on numeric keypad and numbers on top of keyboard.

keyCodes :

numbers on top of keyboard ( 0 - 9 ) : 48 - 57
numbers on numeric keypad ( 0 - 9 ) : 96 - 105

JavaScript condition :

if((e.keyCode >= 48 && e.keyCode <=57) || (e.keyCode >= 96 && e.keyCode <=105)) { 
    // entered key is a number
}

Reference for all keycodes ( with demo ) : http://www.codeforeach.com/javascript/keycode-for-each-key-and-usage-with-demo

Splint answered 26/10, 2016 at 11:20 Comment(0)
B
2

For the people that want a CTRL+C, CTRL-V solution, here you go:

    /**
     * Retrieves the number that was pressed on the keyboard.
     *
     * @param {Event} event The keypress event containing the keyCode.
     * @returns {number|null} a number between 0-9 that was pressed. Returns null if there was no numeric key pressed.
     */
    function getNumberFromKeyEvent(event) {
        if (event.keyCode >= 96 && event.keyCode <= 105) {
            return event.keyCode - 96;
        } else if (event.keyCode >= 48 && event.keyCode <= 57) {
            return event.keyCode - 48;
        }
        return null;
    }

It uses the logic of the first answer.

Blowy answered 9/4, 2018 at 12:49 Comment(0)
C
2

To add to some of the other answers, note that:

  • keyup and keydown differ from keypress
  • if you want to use String.fromCharCode() to get the actual digit from keyup, you'll need to first normalize the keyCode.

Below is a self-documenting example that determines if the key is numeric, along with which number it is (example uses the range function from lodash).

const isKeypad = range(96, 106).includes(keyCode);
const normalizedKeyCode = isKeypad ? keyCode - 48 : keyCode;
const isDigit = range(48, 58).includes(normalizedKeyCode);
const digit = String.fromCharCode(normalizedKeyCode);
Caridadcarie answered 19/8, 2019 at 15:42 Comment(3)
This answer solved my problem; for some reason keyCode for numpad 2 was giving the value b when using String.fromCharCode().Quadric
Or, after your answer is understood: String.fromCharCode( (e.which > 95 && e.which < 107 ? e.which - 48 : e.which )).match(/\d/);Chaplain
Note: using range makes the code less efficient, not just because it's calling another function but because it's unnecessarily creating an array with all those numbers instead of just comparing >= 96 and <= 106Amarillis
H
2

Yes, they are different and while many people have made a great suggestion of using console.log to see for yourself. However, I didn't see anyone mention event.location that you can use that to determine if the number is coming from the keypad event.location === 3 vs the top of the main keyboard / general keys event.location === 0. This approach would be best suited for when you need to generally determine if keystrokes are coming from a region of the keyboard or not, event.key is likely better for the specific keys.

Harvester answered 31/3, 2020 at 14:11 Comment(0)
I
1

You can use the key code page in order to find the:

event.code

to diference the number keyboard.

https://keycode.info/

function getNumberFromKeyEvent(event) {
   if (event.code.indexOf('Numpad') === 0) {
      var number = parseInt(event.code.replace('Numpad', ''), 10);
      if (number >= 0 && number <= 9) {
           // numbers from numeric keyboard
      }
   }
}
Incubation answered 23/10, 2019 at 19:53 Comment(0)
B
1

Docs says the order of events related to the onkeyxxx event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

If you use like below code, it fits with also backspace and enter user interactions. After you can do what you want in onKeyPress or onKeyUp events. Code block trigger event.preventDefault function if the value is not number,backspace or enter.

onInputKeyDown = event => {
    const { keyCode } = event;
    if (
      (keyCode >= 48 && keyCode <= 57) ||
      (keyCode >= 96 && keyCode <= 105) ||
      keyCode === 8 || //Backspace key
      keyCode === 13   //Enter key
    ) {
    } else {
      event.preventDefault();
    }
  };
Bridging answered 6/5, 2020 at 11:26 Comment(0)
S
0

The answer by @.A. Morel I find to be the best easy to understand solution with a small footprint. Just wanted to add on top if you want a smaller code amount this solution which is a modification of Morel works well for not allowing letters of any sort including inputs notorious 'e' character.

function InputTypeNumberDissallowAllCharactersExceptNumeric() {
  let key = Number(inputEvent.key);
  return !isNaN(key);
}
Slop answered 1/8, 2018 at 14:24 Comment(0)
P
0

Little bit cleared @A.Morel's answer. You might beware of keyboard language layout. Some keyboard layouts changed default numeric keys to symbols.

let key = parseInt(e.key)
if (isNaN(key)) {
  console.log("is not numeric")
}
else {
  console.log("is numeric")
}
Pavonine answered 16/12, 2020 at 4:40 Comment(1)
Or just : console.log( parseInt(e.key) >= 0 ? "is numeric" : "is not numeric" )Eckard
S
0

You need to check event.key converted to a number is between 0-9. So we can create a range array 0-9 by Array.from(Array(10).keys()) and check the event.key is in this range or not.

const isNumeric = Array.from(Array(10).keys()).includes(Number(event.key));
Schwaben answered 21/1, 2023 at 14:46 Comment(1)
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Tetramethyldiarsine
B
0

**event keyCode values for numeric keypad

function digitOnly(event) {
            var key = event.keyCode;
            if (event.key === '!' || event.key === '@' || event.key === '#'
                    || event.key === '$' || event.key === '%'
                    || event.key === '^' || event.key === '&'
                    || event.key === '*' || event.key === '('
                    || event.key === ')' || event.key === '_'
                    || event.key === '-') {
                return false;
            }

            if ((key >= 48 && key <= 57)
                    || (key >= 96 && key <= 105 || key == 8)) {
                return true;
            } else {
                return false;
            }
        };
<div id="phoneDiv">
                <label for="phoneNumberId">Phone<b id="starText">*</b></label> <input
                    id="phoneNumberId" type="tel" name="phoneNumber"
                    placeholder="Enter Phone Number here" maxlength="10" minlength="10"
                    onkeydown="return digitOnly(event)" required>
            </div>

**

Barde answered 15/2, 2024 at 5:32 Comment(0)
G
-2

You can use this to figure out keyCodes easily:

$(document).keyup(function(e) {
    // Displays the keycode of the last pressed key in the body
    $(document.body).html(e.keyCode);
});

http://jsfiddle.net/vecvc4fr/

Gdynia answered 11/9, 2014 at 14:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.