21

Why isn't backspace being detected using jQuery keypress event?

$("#field").keypress(function(event){alert(event.which);});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Babiker
  • 18,300
  • 28
  • 78
  • 125

3 Answers3

21

Try using keydownand keyupfunctions instead for IE.

Javascript e.keyCode doesn't catch Backspace/Del in IE

Community
  • 1
  • 1
mdarwi
  • 913
  • 4
  • 9
19

The "keypress" event is (in its original IE form, and in Safari/Chrome) about an actual character being added to a text field. The backspace key clearly does not add a new character to the field value, so it causes no keypress event.

Firefox and Opera are a little more willy-nilly about generating typing events.

PPK (quirksmode) considers the IE and Webkit behaviors to be the sensible ones, and I pretty much agree.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • It may be sensible, but it decreases the usefulness of the event IMO. Maybe it's just habit, but I often use keypress (in other languages, where the event fires if the pressed key has an ASCII value) trap the BS key to do things like disable buttons when the user backs all the text out of an input box. – BobRodes Aug 11 '13 at 20:11
0

The onKeyUp alone will do all the keyboard key detection in chrome..