简体   繁体   中英

How to handle two submit buttons in my form

I am trying to create two submit button in my form

<form id="form-input-wrapper" action='test.php'>

//form items..
//form items..

    <button class="btn btn-primary" type="submit" value="old">first button.</button>

    <button class="btn btn-primary" type="submit" value="new">second button</button>
</form>

My question is how to distinquish which button the user clicks in my test.php page?

You need to add the name attribute to your buttons

<button class="btn btn-primary" type="submit" name="old" value="old">first button.</button>

<button class="btn btn-primary" type="submit" name="new" value="new">second button</button>

The php code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //something posted

    if (isset($_POST['old'])) {
        //old
    } elseif (isset($_POST['new']){
        //new
    }
}

related question: How can I tell which button was clicked in a PHP form submit?

Use button name tag and check them in php:

<button name="subject1" type="submit" value="HTML">HTML</button>
<button name="subject2" type="submit" value="CSS">CSS</button>

And in php:

<?php
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     if ( isset($_POST['subject1']) )   {
       // first button is clicked

     } elseif ( isset($_POST['subject2']) )   {
        //second button is clicked

     }
  }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM