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.

Sign up to request clarification or add additional context in comments.

4 Comments

Add type="submit" to the buttons.
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.
Not for old versions of IE (don't know exactly which ones).
@azeós The sooner we forget about them the sooner the world will be a better place. I have edited my answer accordingly.
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 Comments

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
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.