defeating the enter key from doing a form submit
I've found several jQue开发者_运维百科ry 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?
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/
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();
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
});
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;
});
精彩评论