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 =)
Use the
keypressevent instead ofkeyup. 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.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.