1

I need to capture that pressed key is 0-9 including numbers from numpad. I wrote a function that checks it but it doesn't work on numpad digits

function getKeyVal(e) {
   var order = String.fromCharCode(e.keyCode);
   return /^\s*\d+\s*$/.test(order)
}

String.fromCharcode return "a" from numpad key 1.

Can anybody help?

exexzian
  • 7,782
  • 6
  • 41
  • 52
  • 1
    See http://www.quirksmode.org/js/keys.html and many similars. Getting character pressed is much more tricky, so your assuption that String.fromCharCode(e.keyCode) is always correct is unfortunatelly wrong. – Danubian Sailor May 15 '13 at 08:50

2 Answers2

0

You can use the onkeypress handler, or subtract 48 from the keycode. See this question:

Get Correct keyCode for keypad(numpad) keys

Community
  • 1
  • 1
Zissou
  • 227
  • 1
  • 8
0

KeyboardEvent.keyCode is deprecated and no longer recommended. KeyboardEvent.code or KeyboardEvent.key should be used. KeyboardEvent.code property represents a physical key on the keyboard. KeyboardEvent.key property returns the value of the key.

Examples:

KeyboardEvent.code: If 1 is pressed on Numpad it will return Numpad1.

KeyboardEvent.key: If 1 is pressed on Numpad it will return 1.

If you want only to get keys from Numpad or the Digit keys, Check if indexOf Numpad/Digit is greater than -1. Your function will be as following:

function getKeyVal(e) {
  if (e.code.indexOf('Numpad') > -1 || e.code.indexOf('Digit') > -1) {
    return e.key;
  }
}

Otherwise simply use e.key or function as:

function getKeyVal(e) {
  return e.key;
}
Muhammad Zohaib
  • 307
  • 1
  • 5
  • 15