views:

107

answers:

4

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;
    }
  });
}
+9  A: 

Try this:

$(function() {
    $("form").submit(function() { return false; });
});
icktoofay
Works great, thank you icktoofay!
Sharon
A: 

Why would you want to remove the functionality that almost all users will expect?

Allyn
He might be trying to make it do something with AJAX rather than have the browser deal with it.
icktoofay
@icktoofay: If this is for Ajax then the way to deal with that is to bind an event to the form submit, not mangle keyboard input.
Aaronaught
@Aaronaught: I know; and that's what I posted as my answer.
icktoofay
+2  A: 

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
A: 

add onSubmit property on form's tag.

<form onSubmit="return false;">
PatlaDJ