[html] Two submit buttons in one form

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

This question is related to html forms submit

The answer is


This is extremely easy to test

<form action="" method="get">

<input type="submit" name="sb" value="One">
<input type="submit" name="sb" value="Two">
<input type="submit" name="sb" value="Three">

</form>

Just put that in an HTML page, click the buttons, and look at the URL


I think you should be able to read the name/value in your GET array. I think that the button that wasn't clicked wont appear in that list.


<form>
    <input type="submit" value="Submit to a" formaction="/submit/a">
    <input type="submit" value="submit to b" formaction="/submit/b">    
</form>

<form method="post">
<input type="hidden" name="id" value="'.$id.'" readonly="readonly"/>'; //any value to post PHP
<input type='submit' name='update' value='update' formAction='updateCars.php'/>
<input type='submit' name='delete' value='delete' formAction='sqlDelete.php'/>
</form>

There’s a new HTML5 approach to this, the formaction attribute:

<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>

Apparently this does not work in IE9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).

Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.

Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.

Edit: As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.


Define name as array.

<form action='' method=POST>
    (...) some input fields (...)
    <input type=submit name=submit[save] value=Save>
    <input type=submit name=submit[delete] value=Delete>
</form>

Example server code (PHP):

if (isset($_POST["submit"])) {
    $sub = $_POST["submit"];

    if (isset($sub["save"])) {
        // save something;
    } elseif (isset($sub["delete"])) {
        // delete something
    }
}

elseif very important, because both will be parsed if not. Enjoy.


HTML example to send different form action on different button click:

<form action="/login" method="POST">
        <input type="text" name="username" value="your_username" />
        <input type="password" name="password" value="your_password" />
        <button type="submit">Login</button>
        <button type="submit" formaction="/users" formmethod="POST">Add User</button>
</form>

Same form is being used to add a new user and login user.


Simple you can change the action of form on different submit buttons Click.

Try this in document.Ready

$(".acceptOffer").click(function () {
       $("form").attr("action", "/Managers/SubdomainTransactions");
});

$(".declineOffer").click(function () {
       $("form").attr("action", "/Sales/SubdomainTransactions");
});

You can also use a href attribute and send a get with the value appended for each button. But the form wouldn't be required then

href="/SubmitForm?action=delete"
href="/SubmitForm?action=save"

You formaction for multiple submit button in one form example

 <input type="submit" name="" class="btn action_bg btn-sm loadGif" value="Add Address" title="" formaction="/addAddress"> 
 <input type="submit" name="" class="btn action_bg btn-sm loadGif" value="update Address" title="" formaction="/updateAddress"> 

You can also do it like this (I think it's very convenient if you have N inputs).

<input type="submit" name="row[456]" value="something">
<input type="submit" name="row[123]" value="something">
<input type="submit" name="row[789]" value="something">

A common use case would be using different ids from a database for each button, so you could later know in the server wich row was clicked.

In the server side (PHP in this example) you can read "row" as an array to get the id. $_POST['row'] will be an array with just one element, in the form [ id => value ] (for example: [ '123' => 'something' ]).

So, in order to get the clicked id, you do:

$index = key($_POST['row']);

http://php.net/manual/en/function.key.php


The best way to deal with multiple submit button is using switch case in server script

<form action="demo_form.php" method="get">

Choose your favorite subject:

<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">Java Script</button>
<button name="subject" type="submit" value="jquery">jQuery</button>

</form>

server code/server script - where you are submitting the form:

demo_form.php

<?php

switch($_REQUEST['subject']) {

    case 'html': //action for html here
                break;

    case 'css': //action for css here
                break;

    case 'javascript': //action for javascript here
                        break;

    case 'jquery': //action for jquery here
                    break;
}

?>

Source: W3Schools.com


Use the formaction HTML attribute (5th line):

<form action="/action_page.php" method="get">
    First name: <input type="text" name="fname"><br>
    Last name: <input type="text" name="lname"><br>
    <button type="submit">Submit</button><br>
    <button type="submit" formaction="/action_page2.php">Submit to another page</button>
</form>

Maybe the suggested solutions here worked in 2009, but ive tested all of this upvoted answers and nobody is working in any browsers.

only solution i found working is this: (but its a bit ugly to use i think)

<form method="post" name="form">
<input type="submit" value="dosomething" onclick="javascript: form.action='actionurl1';"/>
<input type="submit" value="dosomethingelse" onclick="javascript: form.action='actionurl2';"/>


You can present the buttons like this:

<input type="submit" name="typeBtn" value="BUY">
<input type="submit" name="typeBtn" value="SELL">

And then in the code you can get the value using:

if request.method == 'POST':
    #valUnits = request.POST.get('unitsInput','')
    #valPrice = request.POST.get('priceInput','')
    valType = request.POST.get('typeBtn','')

(valUnits and valPrice are some other values I extract from the form that I left in for illustration)


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
}

Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):

<button type="submit" name="register">Create a new account</button>
<button type="submit" name="login">Log into your account</button>

Rather than using the value to determine which button was pressed, you can use the name (with the <button> tag instead of <input>). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL. In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has **kwargs for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:

if "register" in kwargs:
    pass #Do the register code
elif "login" in kwargs:
    pass #Do the login code

An even better solution consists of using button tags to submit the form:

<form>
    ...
    <button type="submit" name="action" value="update">Update</button>
    <button type="submit" name="action" value="delete">Delete</button>
</form>

The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).


Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for PHP

_x000D_
_x000D_
<?php_x000D_
   if(isset($_POST["loginForm"]))_x000D_
   {_x000D_
    print_r ($_POST); // FOR Showing POST DATA_x000D_
   }_x000D_
   elseif(isset($_POST["registrationForm"]))_x000D_
   {_x000D_
    print_r ($_POST);_x000D_
   }_x000D_
   elseif(isset($_POST["saveForm"]))_x000D_
   {_x000D_
    print_r ($_POST);_x000D_
   }_x000D_
   else{_x000D_
_x000D_
   }_x000D_
?>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
  _x000D_
  <fieldset>_x000D_
    <legend>FORM-1 with 2 buttons</legend>_x000D_
      <form method="post" >_x000D_
      <input type="text" name="loginname" value ="ABC" >_x000D_
_x000D_
     <!--Always use type="password" for password --> _x000D_
     <input type="text" name="loginpassword" value ="abc123" >_x000D_
     _x000D_
     <input type="submit" name="loginForm" value="Login"><!--SUBMIT Button 1 -->_x000D_
     <input type="submit" name="saveForm" value="Save">  <!--SUBMIT Button 2 -->_x000D_
   </form>_x000D_
  </fieldset>_x000D_
_x000D_
_x000D_
_x000D_
  <fieldset>_x000D_
    <legend>FORM-2 with 1 button</legend>_x000D_
     <form method="post" >_x000D_
      <input type="text" name="registrationname" value ="XYZ" >_x000D_
      _x000D_
     <!--Always use type="password" for password -->_x000D_
     <input type="text" name="registrationpassword" value ="xyz123" >_x000D_
     _x000D_
     <input type="submit" name="registrationForm" value="Register"> <!--SUBMIT Button 3 -->_x000D_
   </form>_x000D_
  </fieldset>_x000D_
  _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Forms

When click on Login -> loginForm

When click on Save -> saveForm

When click on Register -> registrationForm


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to submit

React - clearing an input value after form submit angular2 submit form by pressing enter without submit button spark submit add multiple jars in classpath jQuery's .on() method combined with the submit event Selenium Webdriver submit() vs click() PHP form - on submit stay on same page Disable submit button ONLY after submit HTML - How to do a Confirmation popup to a Submit button and then send the request? HTML form with multiple "actions" Javascript change color of text and background to input value