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.

Advertisements
Published in: on June 24, 2014 at 1:27 am  Leave a Comment  

The URI to TrackBack this entry is: https://blackbeltreview.wordpress.com/2014/06/24/using-jquery-to-designate-a-submit-button-as-default-button/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: