Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are three keyboard events you can trap: <code>keyup</code>, <code>keydown</code>, and <code>keypress</code>. The first two behave the way you've observed, and the latter behaves the way you seem to want.</p> <p>You need to understand the difference between a key and the character(s) associated with that key.</p> <p>As explained in the <a href="http://api.jquery.com/keydown/">jQuery doco</a> (admittedly it is kind of buried), the <code>keyup</code> and <code>keydown</code> events give a keyCode that corresponds to the actual physical key on the keyboard, so uppercase "A" and lowercase "a" will have the same code, as will "2" and "@" - but note that the "2" key above the "W" has a different code to the "2" key on the numeric keypad. The <code>event.shiftKey</code> property will tell you whether shift was down at the time the key was pressed. Those two events can also check for non-text type keys like the arrow keys, Ctrl, Home, etc.</p> <p>On the other hand, the <a href="http://api.jquery.com/keypress/"><code>keypress</code></a> event gives a keyCode corresponding to the character, so "A" and "a" will give different keyCodes, as will "2" and "@". <strong>So <a href="http://api.jquery.com/keypress/"><code>keypress</code></a> may be better suited to your needs.</strong></p> <p>(By the way, this isn't a jQuery thing as such, this is normal behaviour even with "plain" JavaScript, though jQuery attempts to normalise behaviour across different browsers. One such normalisation is that jQuery makes sure that <code>event.which</code> will work consistently, so you should use <code>event.which</code> to get the code rather than <code>event.keyCode</code>.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload