Thursday, March 31, 2011

Two submit buttons in one form

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

From stackoverflow
  • 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">
    
  • 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.

    ypnos : You most probably mean the POST array.
    SkippyFire : Either or right?
    Parrots : Not necessarily, if the form's method is "POST" it won't show up in the GET array. Most forms are submitted via POST.
    Bill the Lizard : Either/or is technically right, and yet so wrong. You can submit a form with method="GET", but it is cringeworthy.
    mercator : It is only "cringeworthy" when used inappropriately: http://www.w3.org/2001/tag/doc/whenToUseGet.html.
    SkippyFire : Yeah I wasn't trying to suggest GET, I was just trying to generalize things.
  • Make sure each has an id= attribute. The one used should have a value assigned. Just check and make sure it isn't null and it was the one selected.

  • 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

  • RoBorg is right, but be careful of something - at least IE6 and Firefox3 behave differently when you hit "Enter" to submit instead of clicking a submit button. FF3 seems to send the name/value pair of the first submit input along with the rest of the form, while IE6 doesn't send any of the submit inputs.

  • You can 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 only problem with that is you tie your logic to the text within the input. You could also give each one a unique name and just 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
    }
    

0 comments:

Post a Comment