简体   繁体   中英

Submitting a form with multiple submit values

I have a voting webapp I'm building in PHP, and I'm looking for a straightforward solution to this simple problem (quite a fun problem I think!):

The voting form requires you to enter your email address to vote. I need each vote option to be a submit button.

In pseudo HTML it would look like this:

<form>
  <input type=email>
  <input type=submit name=voteOption1 value=VOTE> 
  <input type=submit name=voteOption2 value=VOTE>
  <input type=submit name=voteOption3 value=VOTE>
</form>

This works fine except for one thing: You will have noticed that the value for each of the submit buttons is VOTE - this cannot be changed . So I get the following from the server:

[email] => hello@example.com
[voteOption1] => VOTE

I need to know which option they voted for (eg. voteOption1 ). Yes, the HTML can be changed.

How would you solve this?

Use an HTML 4 submit button instead of an HTML 3.2 one. Then you can have a different value and display text.

<button name="vote" value="Option 1">
    VOTE
</button>

Thanks for the answers. Another way to solve this is to send a form array. For example:

<form>
  <input type=email>
  <input type=hidden name=voteOption1[option] value=voteOption1>
  <input type=submit name=voteOption1[submit] value=VOTE> 
  <input type=hidden name=voteOption2[option] value=voteOption2>
  <input type=submit name=voteOption2[submit] value=VOTE> 
  <input type=hidden name=voteOption3[option] value=voteOption3>
  <input type=submit name=voteOption3[submit] value=VOTE> 
</form>

So I get the following from the server:

[email] => hello@example.com
[voteOption1] => Array
    (
        [option] => voteOption1
        [submit] => VOTE
    )

[voteOption2] => Array
    (
        [option] => voteOption2
    )

[voteOption3] => Array
    (
        [option] => voteOption3
    )

Then you can simply look for the submit:

foreach ($submittedForm as $data) {
    if (array_key_exists ('submit', $data)) {
        $request->option = $data['option'];
        break;
    }
}

The downside to this is that all elements are submitted, but in this instance that's not a problem.

Am I getting it wrong or do you actually need to check which submit button is clicked?

if (isset($_POST['voteOption1']) {
    // VoteOption1 Clicked
} elseif (isset($_POST['voteOption2']) {
    // VoteOption2 Clicked
} elseif (isset($_POST['voteOption3']) {
    // VoteOption3 Clicked
}
<input type=submit name=voteOption1 value=VOTE1>
<input type=submit name=voteOption2 value=VOTE2>

etc..?

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