In the table below you can enter key strokes and see what codes are generated by the three key events: keydown, keypress, and keyup. Below this are a couple examples restricting data entry using the keypress event based on observation made by entering keystrokes into the table.

The charCode property is only available in the gecko based browsers: Firefox, Mozilla, and Netscape.

Press any key:
  keyCode charCode Character Actual Key
keydown        
keypress        
keyup        

IE does not trigger the keypress event for control and editing keys like arrows, delete, etc. as shown in the "Event sequence" box. It also doesn't trigger keypress when the ALT key is held down. Gecko browsers trigger the keypress event for all keyboard actions returning zero in charCode for control and editing keys and a positive value for printable keys. This makes it easy to identify the control and editing keys. So the keypress event is a good place to restrict what data can be enter into a text field.




The column labelled "Character" is generated by the String.fromCharCode() method using either keyCode or charCode depending which one is non-zero. The String.fromCharCode() method returns incorrect values when used with keydown and keyup event as demonstrated. Those events return a keyboard scan code; where as, keypress returns a character code.

The column labeled "Actual Key" is based on the keydown keyCode value.

If you want to trap control or editing keys they need to be caught using the keydown event. In IE they don't trigger the keypress event, and keys that change focus, like the tab key, do not trigger the original object's keyup event