0

You can get the keyCode of a key pressed in jQuery:

$('#myField').keydown(function(event) {
    console.log(event.which);
});

How do I compare that to a letter? I could, of course, find out the keyCode of that letter, but I don't know ahead of time what that letter is. So I could convert every letter to a keyCode and look that up in an object. I have to imagine there's an easier way for this common situation?

Does myLetter.charCodeAt(0) always give me the same number as event.which for the same letter?

at.
  • 50,922
  • 104
  • 292
  • 461

2 Answers2

1

You need to use String.fromCharCode to convert a Unicode number into a character:

 String.fromCharCode(event.keyCode)
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

I guess you want to use this:

String.fromCharCode();

use it here:

$('#myField').keydown(function(e) {
    var kc = e.which || e.keyCode;
    console.log(String.fromCharCode(kc).toUpperCase() == "A"); // should log true if
    // "A" character is pressed.
});
Jai
  • 74,255
  • 12
  • 74
  • 103