Change Enter from submission to Tab?

后端 未结 3 1425
眼角桃花
眼角桃花 2020-12-03 08:25

Users don\'t like the fact that the Enter key submits the page. So I am tasked with preventing the submission and changing the Enter key to a Tab to the next field.

相关标签:
3条回答
  • 2020-12-03 08:43
    $("input").bind("keydown", function(event) {
    
        if (event.which === 13 && this.type !== 'submit') {
            event.preventDefault();
            $(this).next("input").focus();
        }
    });
    
    0 讨论(0)
  • 2020-12-03 08:55

    Based on this post: http://forum.jquery.com/topic/how-to-find-next-node-in-focus-order

    I came up with this. I eventually chose not to use focasables though, and instead use input to get the effect I wanted. The .not is to prevent image buttons and submit buttons from being effected, so that they still have the default action of submit on enter whenever they have focus.

    $(document).ready(function() {
    var focusables = $(":input").not('[type="image"]').not('[type="submit"]');
    
      focusables.keydown(function(e) {
        if (e.keyCode == 13) {
          e.preventDefault();
          var current = focusables.index(this),
                  next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
          next.focus();
        }
      });
    });
    
    0 讨论(0)
  • 2020-12-03 08:59

    This just feels icky, but you could use event.preventDefault as you mentioned and then call focus() on the next closest input:

    Here's a simple example:

    $("input").bind("keydown", function(event) {
        if (event.which === 13) {
            event.stopPropagation();
            event.preventDefault();
            $(this).next("input").focus();
        }
    });
    

    Example: http://jsfiddle.net/andrewwhitaker/Txg65/

    Update: If you have elements in between your inputs, using plain next() will not work. Instead, use nextAll():

    $("input").bind("keydown", function(event) {
        if (event.which === 13) {
            event.stopPropagation();
            event.preventDefault();
            $(this).nextAll("input").eq(0).focus();
        }
    });
    

    http://jsfiddle.net/andrewwhitaker/GRtQY/

    0 讨论(0)
提交回复
热议问题