JQuery event keypress: which key is pressed? AZ, & @

on keydown I get the following from jQuery:

jQuery.Event
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 the key? I tried:

 String.fromCharCode(e.keyCode)

This works for AZ, but if I press @ I don't get @, do I get 2?

Ideas?

+5
source share
4 answers

There are three keyboard events that you can capture: keyup, keydownand keypress. The first two behave as you noticed, and the last behaves as you think.

You need to understand the difference between the key and the symbol (s) associated with this key.

jQuery doco ( , ), keyup keydown keyCode, , "A" "a" , "2" "@", - , "2" "W" "2" . event.shiftKey , . , , Ctrl, Home ..

, keypress , , "A" "a" keyCodes, "2" "@". keypress .

(, - jQuery, "" JavaScript, jQuery . , jQuery , event.which , event.which , event.keyCode.)

+8

,
http://jsfiddle.net/cSc7r/

,

  String.fromCharCode(key_event.which);

  String.fromCharCode(event.keyCode); // For IE

, - , , . http://jsfiddle.net/zUc4Z/.

+2

All Articles