tags:

views:

64

answers:

4

I've found several jQuery syntaxes for nullifying the enter on a form.

First one:

$("form input[@type=text]").bind("keypress", function(e) {
  var code=e.charCode || e.keyCode;
  return (code==13)?false:true;
});

Second one:

$("form").bind("keypress", function(e) {
   if (e.keyCode == 13) return false;
});

My version:

$('form').keypress(function(e) {
   if (e.which == 13) return false;
});

My question is:

Q: Is my version ok to use, or is there a best practice for defeating the enter key from doing a form submit?

+1  A: 

You want to capture the form's submit event, not focus on how it's submitted. In jQuery you can do this by doing:

$('form').submit(function() {
//do something
return false
});
treeface
Afaik the submit function won't include the keypress event, so there's no way of telling whether the enter key was used to submit the form.
Alec
I suppose it depends on what the OP is asking for. I assumed he meant that he had a form for which he wanted to cancel submission if the user has javascript enabled. In this case, returning false on the submit event would cancel any type of form submission. Of course, if he's trying to cancel the form submission for *only* the enter key, then my answer was useless.
treeface
Yeah, if they click on submit, then that's ok.
cf_PhillipSenn
+1  A: 

In your version you only use e.which which doesn't work in every browser. It's better to include e.keyCode as well, so e.g.:

/*
$('form').keypress(function(e) {
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 13) return false;
});
*/

But the problem here is that it fires every time you use the enter key. Say you have a textarea and you want to enter a line break, than it'd return false, because you're using the enter key within the form element. Same with selecting a drop down option from a select box. So it's probably better to just limit it to the normal input fields:

$('form input[type=text]').keypress(function(e) {
  if (e.which == 13) return false;
});
Alec
jQuery normalizes the which attribute so that it can be reliably used cross-browser. Check the keypress() documentation: http://api.jquery.com/keypress/
Ender
@Ender is correct, you can see it happening here: http://github.com/jquery/jquery/blob/master/src/event.js#L507
Nick Craver
Nice! Good to know.
Alec
+1  A: 

I think your method is probably fine. Capturing the form's submit event won't really help for your situation, because there's no way (that I can think of at least) to know how the form was submitted.

The only suggestion I would make is to change return false; to e.preventDefault();

Ender
+2  A: 

This is an excellent article on how you can prevent default actions from taking place using jQuery.

http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

Ryan French