Enter key press behaves like a Tab in Javascript

后端 未结 22 1235
说谎
说谎 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:14

    Map [Enter] key to work like the [Tab] key

    I've rewritten Andre Van Zuydam's answer, which didn't work for me, in jQuery. This caputures both Enter and Shift+Enter. Enter tabs forward, and Shift+Enter tabs back.

    I've also rewritten the way self is initialized by the current item in focus. The form is also selected that way. Here's the code:

    // Map [Enter] key to work like the [Tab] key
    // Daniel P. Clark 2014
    
    // Catch the keydown for the entire document
    $(document).keydown(function(e) {
    
      // Set self as the current item in focus
      var self = $(':focus'),
          // Set the form by the current item in focus
          form = self.parents('form:eq(0)'),
          focusable;
    
      // Array of Indexable/Tab-able items
      focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
    
      function enterKey(){
        if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
    
          // If not a regular hyperlink/button/textarea
          if ($.inArray(self, focusable) && (!self.is('a,button'))){
            // Then prevent the default [Enter] key behaviour from submitting the form
            e.preventDefault();
          } // Otherwise follow the link/button as by design, or put new line in textarea
    
          // Focus on the next item (either previous or next depending on shift)
          focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
    
          return false;
        }
      }
      // We need to capture the [Shift] key and check the [Enter] key either way.
      if (e.shiftKey) { enterKey() } else { enterKey() }
    });
    

    The reason textarea

    is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of Enter from putting in a new line.

    The reason a and button

    allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.

提交回复
热议问题