Default html button submit on enter with JQuery
I basically needed the update button to be the default action on clicking enter in the form, but there were multiple submit buttons in my form and they weren’t in the order I needed due to UI design. This was a quick and dirty solution to select an html submit button and make it the default when a user clicks enter from certain or all input elements on the form. It could be tweaked to give specific behavior to specific types of input boxes, such as invoking a tab on enter in between required elements, but the general idea is using jQuery to click the default button when the user hits enter.
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
May 5th, 2008 at 10:12 am
Default html button submit on enter with JQuery…
[...]This was a quick solution to select an html submit button and make it the default when a user clicks enter from certain or all input elements on the form using jQuery.[...]…
Nov 20th, 2008 at 2:23 am
testing
Dec 17th, 2008 at 12:46 pm
In using JSF we found that without the return false and return true lines in this example that Firefox worked and IE didn’t behave as we expected. In IE the form was submitted, but we didn’t get the expected action execution on the back end nor the expected JSF error message on the screen. Best I can tell, the return false intercepts the default IE behavior which is to submit the form via the form definition (if that makes sense) as opposed to “pushing the button” which JSF knows which action to call.
Mar 2nd, 2009 at 6:32 am
I’m currently using jQuery 1.3.1. And to make it even more compatible with most of the common situations and less error prone, I’m using the following code:
This uses live so it also will work on newly added elements. And will also work on select elements. And also works on multiple forms. So it searches for the parent form of the element and uses that to find the submit button. As well as button form as input form.
May 24th, 2009 at 3:46 pm
[...] key to the desired behavior when the user presses the ENTER key. I found a good article explaining how to set a form’s default button behavior with JQuery. I did change the code from the article by making it only return true. I did this because returning [...]