Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 670
Zack Peterson Avatar asked Dec 04 '09 15:12

Zack Peterson


3 Answers

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

like image 90
Ikke Avatar answered Nov 13 '22 04:11

Ikke


Or return false;:

$(document).ready(function(){
  ...
  //handle enter key
  $("input").keypress(function (e) {
      var k = e.keyCode || e.which;
      if (k == 13) {
          return false; // !!!
      }
  });
});
like image 42
Mark Ursino Avatar answered Nov 13 '22 05:11

Mark Ursino


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();
        }
    });
});
like image 31
Ben Lesh Avatar answered Nov 13 '22 05:11

Ben Lesh