0

I'm working on HTML input filtering, and I have the following situation:

I need to convert keyCodes to chars, but when I'm dealing with Numpad keys I get weird outcome:

String.fromCharCode(96) //should be 0 but I recieve "`"
String.fromCharCode(97) //should be 1 but I recieve "a"
String.fromCharCode(98) //should be 2 but I receive "b"
String.fromCharCode(99) //should be 3 but I recieve "c"
String.fromCharCode(100) //should be 4 but I recieve "d"
String.fromCharCode(101) //should be 5 but I recieve "e"
String.fromCharCode(102) //should be 6 but I recieve "f"
String.fromCharCode(103) //should be 7 but I recieve "g"

From documentation and from event debugging I can see the following mapping:

numpad 0    96
numpad 1    97
numpad 2    98
numpad 3    99
numpad 4    100
numpad 5    101
numpad 6    102
numpad 7    103 

link: https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

What am I missing here?

ecoologic
  • 10,202
  • 3
  • 62
  • 66
Pavel Durov
  • 1,287
  • 2
  • 13
  • 28
  • 1
    Check out this answer : https://stackoverflow.com/questions/5630918/get-correct-keycode-for-keypadnumpad-keys/42917149#42917149 – sudip Jan 14 '18 at 22:38
  • Please show the [MCVE] code you're using, that way we can more easily provide you with a working answer. – David Thomas Jan 14 '18 at 22:41
  • https://stackoverflow.com/questions/5630918/get-correct-keycode-for-keypadnumpad-keys – Red Mercury Jan 14 '18 at 22:45
  • What Minimal, Complete, and Verifiable example? Just execute String.fromCharCode(103) and you'll get an example – Pavel Durov Jan 14 '18 at 22:57

3 Answers3

1

Use the ASCII table to get char codes.

Sergey Benzenko
  • 280
  • 2
  • 14
0

Might just be a silly mistake. Charcode you should see is 48-57 for the numbers.

for ( let i = 0; i < 10; i++ ) {
  console.log( String.fromCharCode( 48 + i ) );
}

See man ascii

Michael Mikowski
  • 1,269
  • 1
  • 10
  • 21
0

Ok, so accordingly to several sources from the web I should do the following logic:

if(keyCode >= 96 && keyCode <= 105){
    keyCode -= 48;
}

Wierd that String.fromCharCode function docs doens't say anything about it :(

Pavel Durov
  • 1,287
  • 2
  • 13
  • 28