I want to capture the TAB keypress, cancel the default action and call my own javascript function.
Edit: Since your element is dynamically inserted, you have to use delegated on() 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:
$("#parentOfTextbox").on('keydown', '#textbox', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
// call custom function here
}
});
Check an example here.
$('#textbox').live('keypress', function(e) {
if (e.keyCode === 9) {
e.preventDefault();
// do work
}
});
Suppose you have TextBox with Id txtName
$("[id*=txtName]").on('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
alert('Tab Pressed');
}
});
This worked for me:
$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });
An important part of using a key down on tab is knowing that tab will always try to do something already, don't forget to "return false" at the end.
Here is what I did. I have a function that runs on .blur and a function that swaps where my form focus is. Basically it adds an input to the end of the form and goes there while running calculations on blur.
$(this).children('input[type=text]').blur(timeEntered).keydown(function (e) {
var code = e.keyCode || e.which;
if (code == "9") {
window.tabPressed = true;
// Here is the external function you want to call, let your external
// function handle all your custom code, then return false to
// prevent the tab button from doing whatever it would naturally do.
focusShift($(this));
return false;
} else {
window.tabPressed = false;
}
// This is the code i want to execute, it might be different than yours
function focusShift(trigger) {
var focalPoint = false;
if (tabPressed == true) {
console.log($(trigger).parents("td").next("td"));
focalPoint = $(trigger).parents("td").next("td");
}
if (focalPoint) {
$(focalPoint).trigger("click");
}
}
});
Try this:
$('#contra').focusout(function (){
$('#btnPassword').focus();
});