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.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Bernhard Kraus
  • 329
  • 1
  • 3
  • 21

2 Answers2

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');
  }
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
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;
    }
});
XCS
  • 27,244
  • 26
  • 101
  • 151
  • `e.preventDefault()` *and* `return false`. Why?` – Roko C. Buljan Jan 22 '15 at 08:43
  • 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. – XCS Jan 22 '15 at 08:47
  • 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. – Bernhard Kraus Jan 22 '15 at 08:47
  • If you want to understand more about `preventDefault` and `return false`: http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – XCS Jan 22 '15 at 08:50
  • *"returning false would be enough"* you don't understand `return false.` – Roko C. Buljan Jan 22 '15 at 08:50
  • @RokoC.Buljan Take a look at the link I posted. – XCS Jan 22 '15 at 08:50
  • Also, you should know that `e.which` is normalized. so no need to `e.keyCode`. – Roko C. Buljan Jan 22 '15 at 08:53