11

I need to capture a tab keypress event on some dynamic inputs, but the normal syntax using the keypress event doesn't seem to be catching the key code.

$('input').live('keypress', function (e) {
   if ( e.which == 9 )
       alert( 'Tab pressed' );
});

This seems to be catching 0 as the keypress when I go through the debugger in firebug no matter which key I press.

MacAnthony
  • 4,471
  • 2
  • 23
  • 26

2 Answers2

25

Try it with .keyCode instead of .which:

$('input').live('keypress', function (e) {
   if ( e.keyCode == 9 ){
       alert( 'Tab pressed' );
    }
});

Seem to work ;)

RedYeti
  • 1,024
  • 14
  • 28
Strae
  • 18,807
  • 29
  • 92
  • 131
9

Try listening for keyup or keydown instead of keypress (per this SO post)

Community
  • 1
  • 1
brettkelly
  • 27,655
  • 8
  • 56
  • 72
  • 1
    Indeed. quirksmode also has information on browser compatibility of the events, and particular browser quirks with certain keys. I've opted for `keydown` in my code. – Josh Smith Nov 09 '10 at 03:36