Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: event.which and charCodeAt working together

I take what the user typed using event.which on a keypress, and output using String.fromCharCode.

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

For numbers and letters I can handle, but when talking about special characters, I get totally different outputs.

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

After a research, I came across the function charCodeAt, and using this one, the output comes perfectly, even special characters.

Unfortunately, I can't use charCodeAt because the user types directly from the $(document), and not from a field.

So, the question is, is there a way I can get the right charCode from the keyPress event.which?

If still can't figure out my doubt, I made you a Fiddle =)

like image 241
BernaMariano Avatar asked May 24 '12 20:05

BernaMariano


People also ask

What is the difference between keyCode and charCode?

keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event. event. charCode: Returns the Unicode value of a character key pressed during a keypress event.

What is charCode of?

The charCode property returns the Unicode character code of the key that triggered the onkeypress event. The Unicode character code is the number of a character (e.g. the number "97" represents the letter "a"). Tip: For a list of all Unicode characters, please study our Complete Unicode Reference.

What does string fromCharCode do in JavaScript?

In JavaScript, fromCharCode() is a string method that is used to create a string from a sequence of Unicode values. Because the fromCharCode() method is a static method of the String constructor, it must be invoked through the String constructor object rather than through the particular instance of the String class.

What is event which in JavaScript?

Definition and UsageThe which property returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event.


1 Answers

Use the keypress event instead of keyup. It reports character code instead of key codes, and it triggers when actual characters are typed, not when a key is released, so it handles repeated characters too.

$('#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 keypresses everywhere, you have to hook up the event on the document, and also on any elements that consumes keypresses. A textbox for example will handle the keypress and won't let it bubble up to the parent element.

like image 86
Guffa Avatar answered Sep 28 '22 07:09

Guffa