Lets see some fact tables:
| Key: a | keyDown | keyPress |
|---|---|---|
| e.which | 65 | 65 |
| e.charCode | 0 | 65 |
| e.keyCode | 65 | 0 |
And String.fromCharCode(65) is “a”, so correct. However when it comes to upper cases:
| Key: A | keyDown | keyPress |
|---|---|---|
| e.which | 65 | 97 |
| e.charCode | 0 | 97 |
| e.keyCode | 65 | 0 |
So to detect a “A”, keyDown can only detect a “shift” and an “a”. We need to rely on keyPress here.
However for control keys, keyPress doesn’t work that well.
| Key: ESC | keyDown | keyPress |
|---|---|---|
| e.which | 27 | 0 |
| e.charCode | 0 | 0 |
| e.keyCode | 27 | 27 |
| Key: ESC | keyDown | keyPress |
|---|---|---|
| e.which | 16 | Undetectable |
| e.charCode | 0 | Undetectable |
| e.keyCode | 16 | Undetectable |
So all in all:
- Use
event.whichwithString.fromCharCode(num); - Use
keyDownfor Controls,keyPressfor Character detection.
Also, pay attention to the detection of BackSpace. Use e.preventDefault(); to prevent Firefox from navigating back.
