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
2009-08-21 22:23:23
Also, to cancel the default action, use e.preventDefault(); in the first line of the function.
Josh Leitzel
2009-08-21 22:26:34
this isn't working for me in IE6+
Jon Erickson
2009-08-21 22:33:24
@Jon, keypress doesn't capture noncharacter keys in IE
Marc
2009-08-21 22:34:56
@Marc I see that, how can I be compatible with IE and FF?
Jon Erickson
2009-08-21 22:42:04
^^ The irony... jQuery is supposed to bridge the gap between broswers, so that you don't have to worry about stuff like this.
Jagd
2009-08-21 22:57:49
@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
2009-08-21 23:20:12
+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
2009-08-21 22:28:07
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
2009-08-21 22:55:03
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
2009-08-21 23:01:11
yea the textbox is dynamically inserted. my example with id #textbox was just to simplify the question =)
Jon Erickson
2009-08-21 23:29:25
@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
2009-08-22 00:58:33