4

Is it possible to submit hidden name value pair based on which button is clicked?

Here's my form:

<form action="POST" action="">
    <button>
        <input type="hidden" name="vote" value="up"/>
        vote up!
    </button>
    <button>
        <input type="hidden" name="vote" value="down"/>
        vote down
    </button>
</form> 

For some reason, the name value pair I received was always the latter (the first one got replaced). For example a user clicked on 'vote down', I still get $input['vote'] = up

Does anyone know how to fix this?

2 Answers 2

5

Normally to work with multiple submit buttons, you would just give each button a name and value:

<form action="post" action="">
    <button type="submit" name="vote" value="up">vote up!</button>
    <button type="submit" name="vote" value="down">vote down!</button>
</form>

Only one button can be submitted, so only one of these values will be sent. At the receiving end, the script neither knows nor cares what type of input you used, so it will see the result you want.

Edit: I added type="submit" for completeness, though that should be unnecessary.

4
  • Add type="submit" to the buttons.
    – azeós
    Commented Jul 24, 2016 at 2:32
  • For better or worse, the default type of button is submit, so that’s not necessary. I agree, though, that adding it would make the purpose clearer.
    – Manngo
    Commented Jul 24, 2016 at 2:36
  • Not for old versions of IE (don't know exactly which ones).
    – azeós
    Commented Jul 24, 2016 at 2:39
  • 1
    @azeós The sooner we forget about them the sooner the world will be a better place. I have edited my answer accordingly.
    – Manngo
    Commented Jul 24, 2016 at 2:42
3

This is because you put both of them in the form so the parameters received by server will look like

vote=up&vote=down

Assume that you access it using php associative array you will always received the latest value in the entries having the same key. That aside, why not just

<form action="POST" action="">
<button>
    <input type="hidden" name="vote" value="up"/>
    vote up!
</button>
</form> 

<form action="POST" action="">
<button>
    <input type="hidden" name="vote" value="down"/>
    vote down
</button>
</form> 
2
  • Thanks. But that's kinda redundant. I guess the only way is using javascript then if I want to combine them in one form. Can you think of other alternatives without using javascript? because I want to avoid javascript submit whenever possible Commented May 15, 2015 at 14:44
  • You cannot do that in a single form with the kind of button design without javascript. If you insist on having two elements in a form, they both will always be submitted. If you want you can always remove form and create 2 linked buttons
    – mimimi
    Commented May 15, 2015 at 15:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.