I have the following javascript in my page which does not seem to be working.
$('form').bind("keypress", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.
This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.
The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.
If
keyCode
is not caught, catchwhich
:EDIT: missed it, it's better to use
keyup
instead ofkeypress
EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.
EDIT 3: Changed
bind()
toon()
When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.
Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :
which
docs.