Enter key press behaves like a Tab in Javascript

后端 未结 22 1256
说谎
说谎 2020-11-27 10:52

I\'m looking to create a form where pressing the enter key causes focus to go to the \"next\" form element on the page. The solution I keep finding on the web is...

22条回答
  •  再見小時候
    2020-11-27 11:37

    Changing this behaviour actually creates a far better user experience than the default behaviour implemented natively. Consider that the behaviour of the enter key is already inconsistent from the user's point of view, because in a single line input, enter tends to submit a form, while in a multi-line textarea, it simply adds a newline to the contents of the field.

    I recently did it like this (uses jQuery):

    $('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
     if (e.keyCode==13) {
      var focusable = $('input,a,select,button,textarea').filter(':visible');
      focusable.eq(focusable.index(this)+1).focus();
      return false;
     }
    });
    

    This is not terribly efficient, but works well enough and is reliable - just add the 'enterastab' class to any input element that should behave in this way.

提交回复
热议问题