java_pill
java_pill

Reputation: 843

Wrong form submission using Enter Key when there are two submit buttons

I have a form with two submit buttons - one for Cancel and the other is for Saving form values to the DB . When Enter key is pressed, the Cancel button submits the form instead of the Save button submitting the form. How can I make the Save button submit the form when Enter key is pressed?

Thanks,

Upvotes: 9

Views: 7300

Answers (1)

TNi
TNi

Reputation: 16672

Your form should not have two submit buttons. Have the Save button be of type submit, and the Cancel button be of type button.

EDIT: I'm going to update this answer to handle several issues that were brought up.

Nothing I've seen in the HTML specification (i.e. the DTD) disallows two submit buttons in one form, but the exact issue the OP mentioned can occur. In his or her case, the solution is to make the Cancel button of type button and add in the following JavaScript:

<input type="button" value="Cancel" onclick="window.location.href='nextpage.html';"/>

Here, one would replace nextpage.html with the appropriate URL. Or, this.form.action can be the new location if the redirection is to the action of the form.

If the OP wants to be safe and avoid JavaScript, this could only be a (perhaps styled) hyperlink.

Upvotes: 8

Related Questions