Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

php - Can I get the name of submit button in another form?

I have a form which has 3 submit buttons. Their names are generated and assigned in a loop. Now if I use a post method, how can access the name of the submit button which was clicked.

The following is the example of my code:

**one.php**

    <form name="one" method="post" action="two.php">

    <?php
    while($i=1;$i<=3;$i=$+1)
    {
    ?>
    <button type="submit" name="<?php echo $i ?>" value="<?php echo $i ?>" >
    </button>
    <?php
    }
    ?>

    </form>

**two.php**

    {
    code???????
    }

May be I can use onsubmit attribute for the button tag in one.php, but I am unable to get the output. Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could just check in $_POST if there is an entry with the name of each one of your three buttons :

for ($i=1 ; $i<=3 ; $i++) {
    if (isset($_POST[$i])) {
        // here, you are on the clicked button
    }
}


Note that I'd suggest you give better names (that don't begin with a number) to your buttons -- which means generating your form like this :

<?php for ($i=1 ; $i<=3 ; $i++) { ?>
<button type="submit" name="button_<?php echo $i ?>" value="<?php echo $i ?>" >
</button>
<?php } ?>

And, on form's submission, using something like this :

for ($i=1 ; $i<=3 ; $i++) {
    if (isset($_POST['button_' . $i])) {
        // here, you are on the clicked button
    }
}


BTW: your while loop's syntax is incorrect -- it seems you've mixed up while and for ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...