3

I have a autocomplete textbox in a form and I want to detect whether user has focussed on the textbox from navigating through tab key press.I mean tabindex has been set up on different form fields and user can navigate fields by pressing tabs.Now I want to perform some action when user directly mouse click/foxus on the textbox and some other action when user has focussed on the textbox through tab.

Below is the code I was trying.But no matter everytime code is 0.

$('#tbprofession').on('focus', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 9) {
            alert('Tabbed');
        }
        else 
        {
            alert('Not tabbed');
        }
});

This code does not work.

Note:Before marking duplicate it will be good if you understand the question correctly.Else I can make it more clear with more elaborated description.

Anyone can show me some light?

Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42

3 Answers3

4

You can try something like that :

$(document).on("keyup", function(e) {
  if ($('#tbprofession').is(":focus")) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 9) {
      alert('I was tabbed!');
    } else {
      alert('not tabbed');
    }
  }
});

fiddle : https://jsfiddle.net/xc847mrp/

Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
4

You can use keyup event instead:

$('#tbprofession').on('keyup', function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 9) {
    console.log('I was tabbed!', code);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input autofocus>
<input id='tbprofession'>
Jai
  • 74,255
  • 12
  • 74
  • 103
0

You could have an array of key events triggered anytime a user presses a key while on your page. Although this makes you think of a keylogger. Or just keep the last key. Or a boolean saying if the last key pressed was a TAB or not.

And on focus you can look at that variable.

Petre Ionescu
  • 174
  • 1
  • 8