Margo Eastham
Margo Eastham

Reputation: 655

Html submit value based on which button is clicked

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?

Upvotes: 4

Views: 5076

Answers (2)

Manngo
Manngo

Reputation: 16281

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.

Upvotes: 5

mimimi
mimimi

Reputation: 78

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> 

Upvotes: 3

Related Questions