Enter key press behaves like a Tab in Javascript

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

    In all that cases, only works in Chrome and IE, I added the following code to solve that:

    var key = (window.event) ? e.keyCode : e.which;

    and I tested the key value on if keycode equals 13

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

提交回复
热议问题