Reputation: 1297
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?
Upvotes: 0
Views: 2591
Reputation: 1297
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 :(
Upvotes: 0
Reputation: 1279
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
Upvotes: 0