jQuery Event Keypress: What key was pressed? A-Z, & amp; @


on a keydown I get the following from jQuery:

altKey: false
attrChange: undefined
attrName: undefined
bubbles: true
button: undefined
cancelable: true
charCode: 0
clientX: undefined
clientY: undefined
ctrlKey: false
currentTarget: HTMLDivElement
data: undefined
detail: 0
eventPhase: 2
fromElement: undefined
handleObj: Object
handler: function () {
isDefaultPrevented: function returnFalse() {
jQuery16106168975948821753: true
keyCode: 51
layerX: 0
layerY: 0
metaKey: true
newValue: undefined
offsetX: undefined
offsetY: undefined
originalEvent: KeyboardEvent
pageX: 0
pageY: 0
prevValue: undefined
relatedNode: undefined
relatedTarget: undefined
screenX: undefined
screenY: undefined
shiftKey: false
srcElement: HTMLDivElement
target: HTMLDivElement
timeStamp: 1320206454048
toElement: undefined
type: "keydown"
view: DOMWindow
wheelDelta: undefined
which: 51
__proto__: Object

How can I get what key was pressed? I tried:


That works for A-Z, but if I press @ I don't get @ I get 2?


There are three keyboard events you can trap: keyup, keydown, and keypress. The first two behave the way you've observed, and the latter behaves the way you seem to want.

You need to understand the difference between a key and the character(s) associated with that key.

As explained in the jQuery doco (admittedly it is kind of buried), the keyup and keydown 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 event.shiftKey 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.

On the other hand, the keypress event gives a keyCode corresponding to the character, so "A" and "a" will give different keyCodes, as will "2" and "@". So keypress may be better suited to your needs.

(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 event.which will work consistently, so you should use event.which to get the code rather than event.keyCode.)