Multiple submit button in a form

前端 未结 4 908
挽巷
挽巷 2020-12-21 06:34

Hey I am very new to Web Programming. I have been learning PHP from the past few days and I am stuck at one thing.

I have a form tag in my code which has two submit

相关标签:
4条回答
  • 2020-12-21 07:16

    just as a reference... int HTML5 buttons can redefine the form's action,method,type etc. http://w3schools.com/html5/tag_button.asp for me, that's a good way to control a form :)

    0 讨论(0)
  • 2020-12-21 07:25

    One way is to use Javascript to switch the form's action depending on which control has been clicked. The following example uses the jQuery library:

    <form id="theForm" action="foo.php">
    ...
        <input id="first" type="submit"/>
        <input id="second" type="submit"/>
    </form>​
    
    $(document).ready(function() {
        $("#theForm input").click(function(e) {
            e.preventDefault();
            if(e.target.id == 'first') {
                $("#theForm").attr("action", "somePage.php");
            } else {
                $("#theForm").attr("action", "anotherPage.php");
            }
            alert($("#theForm").attr("action"));
            $("#theForm").submit(); 
        });
    ​});​
    

    Demo here: http://jsfiddle.net/CMEqC/2/

    0 讨论(0)
  • 2020-12-21 07:30

    to add another solution based on @karim79's, since it's tagged with PHP:

    <form id="theForm" action="foo.php">
    ...
        <input id="first" name="button" value="first" type="submit"/>
        <input id="second" name="button" value="second" type="submit"/>
    </form>​
    

    in your foo.php, do something like this:

    <?php
    $submit = isset($_GET['button']) ? trim($_GET['button']) : '';
    
    if($submit == 'first')
    {
       header('Location: somePage.php');
    }
    else if($submit == 'second')
    {
       header('Location: anotherPage.php');
    }
    ?>
    

    Summary: to be able to read on your button (2 submit buttons), you need to add name on each one. To make it simple, just use the same name on both. Then, add different value. Next, you need to know what button is being clicked by checking what value is sent on that particular button.

    0 讨论(0)
  • 2020-12-21 07:37

    But it doesn't seem right for some reason.

    That's wrong assumption.
    Any other solution would be much worst.

    Checking on the server side is the only reliable solution.
    However echo in branches isn't necessary. There are a lot other ways.
    To use include statement is most obvious one.

    0 讨论(0)
提交回复
热议问题