Javascript: event.which and charCodeAt work together

I take what the user input with event.which when a key is pressed, and output using String.fromCharCode.

User Types: a
event.which: 67
Outputs: A

I can refer to numbers and letters, but when it comes to special characters, I get completely different outputs.

User types: -
event.which: 189
Outputs: ½

After researching, I came across the charCodeAt function, and using this, the output is completely, even special characters.

Unfortunately, I cannot use charCodeAt, because the user types directly from $ (document), and not from the field.

So the question is, is there a way to get the correct charCode from the keyPress.which event?

If I still can not understand my doubts, I made you Fiddle =)

+7
source share
2 answers

Use the keypress event instead of keyup . It reports the character code instead of the key codes, and it starts when the actual characters are typed, and not when the key is released, so it also processes repeating characters.

 $('#field').focus().keypress(function(e){ var key = e.which; $("#key").val(String.fromCharCode(key)); }); 

http://jsfiddle.net/Guffa/QCHt7/1/

Edit:

If you want to catch keystrokes everywhere, you need to connect the event to the document, as well as to any elements that consume keystrokes. A text field, for example, will handle keystrokes and will not allow it to navigate to the parent element.

+6
source

You are using keyup, an event that tells which key was pressed, not which character was entered. Instead, you should use keypress like this:

 $(document).keyup(function(e){ console.log(String.fromCharCode(e.which)); }); 

From jquery doc on keyboard :

Please note that keydown and keyup provide a code indicating which key is pressed, and a keystroke indicates which character was entered. For example, the lowercase "a" will be displayed as 65 using keydown and keyup, but as 97 by pressing a key. In upper case, “A” is reported as 65 Events. Because of this difference, when hitting special keystrokes such as arrow keys, .keydown () or .keyup () is the best choice.

+2
source

All Articles