0

Below code accepts a character and prints character using keycode(String.fromCharCode). Issue arises when you enter special character like . or ?.

function logChar(e){
  var keyCode = e.which || e.keyCode;
  var char = String.fromCharCode(keyCode);
  console.log(char)  
}
<input type="text" onkeydown="logChar(event)" />

Can someone explain why is it returning different value and how to get same value?

Thanks in advance!

Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • 2
    onkeydown triggers once when you press shift (with a value of 16) and separately for another key, whose value is not affected by whether you are pressing shift or not. – James Jan 13 '16 at 13:57
  • @James Your point is correct, but even if you do not press `shift`, just press `.`(dot), still you do not get correct character. I guess @Balah's answer explains why. – Rajesh Jan 13 '16 at 15:08

1 Answers1

4

That's because keyCode and charCode are different. String.fromCharCode assumes that the input is unicode (so A is 65), and for the letter and number keys, they will match... sort of. You will notice that 'a' and 'A' as a keyCode both come out as 65, but 'a' is 97! So keyCode is just an identifier for the actual key on the keyboard that you press and is not unicode.

That's why the numpad 0-9 gives different codes too. If you want to map the key presses, use a site like this. But note you will never get the exact character out again.

Balah
  • 2,530
  • 2
  • 16
  • 24