29

Is there a way to make a form NOT refresh or call anything when you hit "Enter" key on your keyboard?

Thank you so much!!!

I found this code for preventing Enter from working, but it DOESN'T work in IE :(

  $(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
}
Sharon
  • 331
  • 2
  • 4
  • 6

4 Answers4

41

Try this:

$(function() {
    $("form").submit(function() { return false; });
});
icktoofay
  • 126,289
  • 21
  • 250
  • 231
25

Disabling the submit event isn't a good idea. Now you can never submit the form by pressing the button where it is for.

Rather hook on the keypress event:

<form onkeypress="return event.keyCode != 13">

or in jQuery flavor:

$('form').keypress(function(event) { 
    return event.keyCode != 13;
}); 

13 is the keyCode of Enter key. This works in all browsers from IE6 up to with all the current ones. You only have to take textareas into account. You may then consider this construct instead:

$(':input:not(textarea)').keypress(function(event) { 
    return event.keyCode != 13;
});
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
21

add onSubmit property on form's tag.

<form onSubmit="return false;">
PatlaDJ
  • 1,226
  • 2
  • 17
  • 31
2

You can prevent form submission by 'enter' key natively if you are using AngularJS.

According to HTML specification and AngularJS, you need to check this list:

  1. Form must have NO action=... attribute (AngularJS handles it automatically)
  2. Form must have NO button with type="submit" attribute

So, if you have no action attribute and submit button, then your form should not be submitted by hitting enter key.

Also, cross-browser keyCode is this:

var code = (e.keyCode ? e.keyCode : e.which);
Maxim Demkin
  • 1,215
  • 11
  • 13