Enter key press behaves like a Tab in Javascript

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

    Thank you for the good script.

    I have just added the shift event on the above function to go back between elements, I thought someone may need this.

    $('body').on('keydown', 'input, select, textarea', function(e) {
    var self = $(this)
      , form = self.parents('form:eq(0)')
      , focusable
      , next
      , prev
      ;
    
    if (e.shiftKey) {
     if (e.keyCode == 13) {
         focusable =   form.find('input,a,select,button,textarea').filter(':visible');
         prev = focusable.eq(focusable.index(this)-1); 
    
         if (prev.length) {
            prev.focus();
         } else {
            form.submit();
        }
      }
    }
      else
    if (e.keyCode == 13) {
        focusable = form.find('input,a,select,button,textarea').filter(':visible');
        next = focusable.eq(focusable.index(this)+1);
        if (next.length) {
            next.focus();
        } else {
            form.submit();
        }
        return false;
    }
    });
    

提交回复
热议问题