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

纵然是瞬间 提交于 2019-12-06 08:54:16
  • 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');
  }
});
  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;
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!