Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyCode values for numeric keypad?

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?

like image 972
DanielAttard Avatar asked Nov 02 '12 14:11

DanielAttard


People also ask

What is e keyCode === 13?

key 13 keycode is for ENTER key.

What is the keyCode for Wasd?

WASD Keyboard Controls keyCode == 65) { //Move player left (using key 'A') moveX = -1; } else if (evt.


2 Answers

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.

like image 193
Rory McCrossan Avatar answered Sep 23 '22 21:09

Rory McCrossan


******************* 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 
like image 22
A. Morel Avatar answered Sep 24 '22 21:09

A. Morel