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 =)
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.
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.
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.
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With