开发者

How Do I Prevent Enter Key Submit in jQuery? [duplicate]

开发者 https://www.devze.com 2022-12-13 10:45 出处:网络
This question already has answers here: Prevent users from submitting a form by hitting Enter (36 answers)
This question already has answers here: Prevent users from submitting a form by hitting Enter (36 answers) Closed 6 years ago.

I'd like to either simply swallow an Enter key press in <input> fields or else instead substitute Tab key presses. I haven't yet decided which is best.

How can I do this in jQuery? I've got this so far:

$(document).ready(function(){
    ...
    //handle enter key
    $("input").keypress(function (e) {
        var k = e.keyCode || e.which;
        if (k == 13) {
            //???
        }
    });
});

(That e.keyCode || e.which part was recommended in this question.)

What might I put there to 开发者_运维知识库either (a) cancel the event or else to (b) force a Tab key press?


With e.preventDefault() you can prevent the default action, which in this case is submiting the form.


Or return false;:

$(document).ready(function(){
  ...
  //handle enter key
  $("input").keypress(function (e) {
      var k = e.keyCode || e.which;
      if (k == 13) {
          return false; // !!!
      }
  });
});


Also, if you'd like to just mimic a tab to the next control, as you mentioned, you could try this method by jdsharp.

$(document).ready(function(){
...
//handle enter key
$("input").keypress(function (e) {
    var k = e.keyCode || e.which;
        if (k == 13) {
            $(this).focusNextInputField();
        }
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消