How to get the key TAB event on an input element?
Asked Answered
R

2

5

I try to trigger a button when in an input field the return key has been hit. This works. But if I hit the tab key nothing is triggered because the TAB key event isn't captured.

Fiddle example

Here is my JQ code snippet for example:

$("input[name=input]").on("keypress, keydown, keyup", function(e) {
  var code = e.keyCode || e.which;
  if ( code == 13 || code == 9 ) {
    $("input[name=btn]").trigger("click");
  }
});

I can't figure out how to get the tab key stroke working like a return key stroke.

Rainie answered 22/1, 2015 at 8:30 Comment(0)
M
7
  • Use Event.preventDefault() to prevent the browser switching focus on Tab press.
  • Listen for "keydown" event only
  • Use KeyboardEvent.key instead

JavaScript's which and keyCode are deprecated, historically they both become a mess.
Even if jQuery normalizes with jQueryEvent.which for both Event.keyCode and Event.which crossbrowser, I think we should abandon the two and use the more human friendly Event.key. What makes more sense, 9 or 'Tab'? 13 or 'Enter'? 42 or... what is 42 anyways

$('input[name=input]').on('keydown', function(evt) {
  if (evt.key === 'Tab' || evt.key === 'Enter') {
    evt.preventDefault();
    $('input[name=btn]').trigger('click');
  }
});
Mcgehee answered 22/1, 2015 at 8:36 Comment(0)
I
5
  1. Only bind the keydown event.
  2. return false and preventDefault on tab key so the focus is not lost.

Demo: http://jsfiddle.net/a08t4o7r/3/

$("input[name=input]").on("keydown", function(e) {
    var code = e.keyCode || e.which;

    if ( code == 13 || code == 9 ) {
        e.preventDefault();
        $("input[name=btn]").trigger("click");
        return false;
    }
});
Immodest answered 22/1, 2015 at 8:41 Comment(7)
e.preventDefault() and return false. Why?`Mcgehee
Well, it also stops propagation. returning false would be enough, but I like having it there, especially in this case (where it's for a submit button and the rest of the function would have to be stopped). The preventDefault is there just for code clarity.Immodest
Thank you. This works just fine. The only thing is that I have to apply a focus change functionality to the function that gets triggered by the button click. If I don't do the user isn't able to change fields with tab.Rainie
If you want to understand more about preventDefault and return false: #1357618Immodest
"returning false would be enough" you don't understand return false.Mcgehee
@RokoC.Buljan Take a look at the link I posted.Immodest
Also, you should know that e.which is normalized. so no need to e.keyCode.Mcgehee

© 2022 - 2024 — McMap. All rights reserved.