HTML form - when I hit enter it refreshes page!

Viewed 42273

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;
    }
  });
}
4 Answers

Try this:

$(function() {
    $("form").submit(function() { return false; });
});

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;
});

add onSubmit property on form's tag.

<form onSubmit="return false;">
Related