Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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,

like image 328
java_pill Avatar asked Jul 08 '10 05:07

java_pill


People also ask

Can there be two submit buttons in a form?

yes, multiple submit buttons can include in the html form. One simple example is given below.

How do you handle multiple submit buttons?

Create another button with type submit. Also add a 'formaction' attribute to this button and give it the value of the secondary URL where you want to send the form-data when this button is clicked. The formaction attribute will override the action attribute of the form and send the data to your desired location.

How do I stop enter key press to submit a web form?

In a simplest way: $("#myinput"). keydown(function (e) { if(e. which == 13) e. preventDefault(); }); The key is to use "keydown" and event.


1 Answers

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.

like image 116
TNi Avatar answered Oct 03 '22 15:10

TNi