views:

2113

answers:

2

I want to capture the TAB keypress, cancel the default action and call my own javascript function.

+3  A: 
$('#textbox').live('keypress', function(e) {
    if (e.keyCode === 9) {
        e.preventDefault();
        // do work
    }
});
Jon Erickson
Also, to cancel the default action, use e.preventDefault(); in the first line of the function.
Josh Leitzel
this isn't working for me in IE6+
Jon Erickson
@Jon, keypress doesn't capture noncharacter keys in IE
Marc
@Marc I see that, how can I be compatible with IE and FF?
Jon Erickson
^^ The irony... jQuery is supposed to bridge the gap between broswers, so that you don't have to worry about stuff like this.
Jagd
@Jagd, jQuery can't infer intent. keypress and keydown are not equivalent for good reason. It just so happens, this situation does not require the distinction.
Marc
+13  A: 

Edit: Since your element is dynamically inserted, you have to use live as in your example, but you should bind it to the keydown event, because as @Marc comments, in IE the keypress event doesn't capture non-character keys:

$('#textbox').live('keydown', function(e) { 
  var keyCode = e.keyCode || e.which; 

  if (keyCode == 9) { 
    e.preventDefault(); 
    // call custom function here
  } 
});

Check an example here.

CMS
+1 for crossbrowser
Marc
this isn't working for me in IE8 =\
Jon Erickson
when I push TAB in IE6+ the event does not fire (it fires on any alphanumeric key though)... I need to use .live('keypress', fn)
Jon Erickson
If only works with live, maybe you are inserting your textbox element dynamically, if the element is already on the page, it will work, check this example: http://jsbin.com/oguhe
CMS
yea the textbox is dynamically inserted. my example with id #textbox was just to simplify the question =)
Jon Erickson
@Jon, the reason you aren't using $(selector).live("keydown", fn) is ? CMS is suggesting using keydown because in IE, keypress does not work for noncharacter keys, (such as Tab)
Marc