[javascript] jQuery: How to capture the TAB keypress within a Textbox

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

This question is related to javascript jquery

The answer is


Try this:

$('#contra').focusout(function (){
    $('#btnPassword').focus();
});

You can capture an event tab using this JQuery API.

$( "#yourInputTextId" ).keydown(function(evt) {
   if(evt.key === "Tab")
      //call your function
});

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");
            }
        }
    });

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');
 }
}); 

Working example in jQuery 1.9:

$('body').on('keydown', '#textbox', function(e) {
    if (e.which == 9) {
        e.preventDefault();
        // do your code
    }
});

Above shown methods did not work for me, may be i am using bit old jquery, then finally the below shown code snippet works for - posting just in case somebody in my same position

$('#textBox').live('keydown', function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();
        alert('tab');
    }
});

This worked for me:

$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });


$('#textbox').live('keypress', function(e) {
    if (e.keyCode === 9) {
        e.preventDefault();
        // do work
    }
});