Quantcast
Viewing latest article 6
Browse Latest Browse All 16

Using jQuery to Designate a Submit Button as Default Button

This article shows you how to assign a Submit button as a default button in an HTML form that has more than one Submit buttons.

A default button allows the user to press ENTER to submit the form. However, if you have more than one Submit buttons in an HTML form, by default, the first button that appears in the UI will be designated as the default button.

Suppose you have a form like this:

<form name="demoForm" method="post" action="/">
 <input type="text" name="txtName">
 <input type="submit" name="btnDelete" value="Delete">
 <input type="submit" name="btnSave" value="Save">
</form>

The default action when the user presses the ENTER key would be the first Submit button that is laid out in the UI. Yes, you’ve guessed it, the default button is “Delete”! Highly undesirable.

How do we set “btnSave” as the default button?

Follow these two steps.

1. Add a class=”defaultButton” to the desirable button. In our case, “btnSave”.

<form name="demoForm" method="post" action="/">
 <input type="text" name="txtName">
 <input type="submit" name="btnDelete" value="Delete">
 <input type="submit" name="btnSave" value="Save"
    class="defaultButton">
</form>

2. Add the following jQuery script which listens to the keypress event.

$(function() {
 $("form input").keypress(function (e) {
 if ((e.which && e.which == 13) 
   || (e.keyCode && e.keyCode == 13)) {
    $('button[type=submit] .defaultButton').click();
    return false;
 } else {
    return true;
 }
 });
});

When the user presses the ENTER, jQuery will simulate a “btnSave” click event (as if the user clicked the Save button on the form). Any other key press will flow through normally.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 6
Browse Latest Browse All 16

Trending Articles