Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two submit buttons in one form

Tags:

html

forms

submit

I have two submit buttons in a form. How do I determine which one was hit serverside?

like image 450
Alex Avatar asked Feb 13 '09 21:02

Alex


People also ask

Can we have 2 submit buttons in a form?

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

How do I use multiple submit buttons in one form?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

How can we use two submit button in one form in PHP?

Having multiple submit buttons and handling them through PHP is just a matter of checking the the name of the button with the corresponding value of the button using conditional statements. In this article I'll use both elseif ladder and switch case statement in PHP to handle multiple submit buttons in a form.

Can I have two or more actions in the same form?

No, a form has only one action.


2 Answers

Solution 1:
Give each input a different value and keep the same name:

<input type="submit" name="action" value="Update" /> <input type="submit" name="action" value="Delete" /> 

Then in the code check to see which was triggered:

if ($_POST['action'] == 'Update') {     //action for update here } else if ($_POST['action'] == 'Delete') {     //action for delete } else {     //invalid action! } 

The problem with that is you tie your logic to the user-visible text within the input.


Solution 2:
Give each one a unique name and check the $_POST for the existence of that input:

<input type="submit" name="update_button" value="Update" /> <input type="submit" name="delete_button" value="Delete" /> 

And in the code:

if (isset($_POST['update_button'])) {     //update action } else if (isset($_POST['delete_button'])) {     //delete action } else {     //no button pressed } 
like image 81
Parrots Avatar answered Oct 05 '22 11:10

Parrots


If you give each one a name, the clicked one will be sent through as any other input.

<input type="submit" name="button_1" value="Click me"> 
like image 33
Greg Avatar answered Oct 05 '22 09:10

Greg