The other day, I was trying to prevent a user from entering certain restricted characters in an input field. The approach was simple: detect which key was being pressed; and, if the key mapped to a restricted character, cancel the default event behavior, thereby preventing the input from being altered. Only, it wasn't working. After a few minutes of debugging, I finally realized that the keydown and keypress events worked differently than I had previously thought.
In jQuery, keyboard-based events build a "which" property into the event object. I had always thought of this property as being the ASCII value of the character being rendered. But, as it turns out, it's a bit more complicated than that.
From what I've read as part of my debugging effort, it seems that the "which" property of the keyboard event represents different things in different event handlers. In the keydown event, the "which" property represents only the key being pressed - not the character being rendered. In the keypress event, on the other hand, the "which" property represents the ASCII value of the character rendered by the keyboard event.
To demonstrate this, I put together some code that logs key codes using both the keydown and keypress events:
With both event types bound, if I focus the input field and type the "?" character (using SHIFT + ?), I get the following messages logged to the console:
keydown : (16)
keydown : (0)
keypress : ? (63)
As you can see, the SHIFT key registered as key code 16 during the keydown event. When I then pressed the "?" key in combination with the SHIFT key, the ASCII value of the question mark character - 63 - was not available until the keypress event.
I've always thought of the keydown and keypress events as being somewhat interchangeable. And, for most situations, they can be. But, when it comes to figuring out which character is going to be rendered - especially those requiring key combinations - you have to listen to the keypress event.
Want to use code from this post? Check out the license.