jQuery: how to capture keypress key using live()

24,032

Solution 1

Try it with .keyCode instead of .which:

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

Seem to work ;)

Solution 2

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

Share:
24,032
MacAnthony
Author by

MacAnthony

Programmer/Project Manager for a consulting company. Other interests: Photography, Poker and American Football

Updated on July 09, 2022

Comments

  • MacAnthony
    MacAnthony almost 2 years

    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.

  • Josh Smith
    Josh Smith over 13 years
    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.