tags:

views:

45

answers:

4

I have a form with two buttons, each with onclick = this.form.submit(). I have a hidden field in the form, and I would like the value of the field to be different based on which button is clicked. What would be the best way to do this?

Also, before anyone says it the answers, jQuery is not an option in this case.

+4  A: 

use Prototype :-)

But in all seriousness:

  1. Add an id to the hidden field
  2. Before you submit the form in each handler:

    document.getElementById("hiddenId").value = "mySpecialValue";

    //or (depending on which onclick handler you are in)

    document.getElementById("hiddenId").value = "myOtherSpecialValue";

  3. Submit the form the same way you are now.

Recommended ex:

<input id="buttonA" type="button" value="do something" onclick="buttonA_clickHandler(event);"/>

...

function buttonA_clickHandler(event) {
    document.getElementById('hiddenId').value = whatever;
    document.getElementById('theForm').submit();
}

repeat for the other button.

geowa4
Can we make the 'use prototype' meme as prevalent on SO as the 'use jquery' one? ;)
Daniel Vandersluis
we can only hope.
geowa4
A: 

Assuming you've got your hidden field setup something like so:

<input type="hidden" name="clicked_button" id="clicked_button" value=""/>

You could just set its value in a common onclick handler for your buttons:

function buttonClick(theButton){
    document.getElementById('clicked_button').value = theButton.name;
    return true;
}

And then your submit buttons would be:

<input type="submit" name="save" value="Save" onclick="return buttonClick(this)"/>
<input type="submit" name="delete" value="Delete" onclick="return buttonClick(this)"/>
Pat
A: 

You could pass the value to which you want to set the hidden input to a function you create:

function handleClick(val){
    document.getElementById('HiddenInputID').value = val;
    return true;
}

and then code the buttons using the onclick to pass whichever value you'd like:

<input type="submit" name="Name1" value="Value 1" onclick="return handleClick('Value 1')"/>
<input type="submit" name="Name2" value="Value 2" onclick="return handleClick('Value 2')"/>
palswim
+1  A: 
  1. Forgive me if the answer to this seems obvious, but why use a hidden field at all? <input type="submit" value="..." /> already works; browsers will send the value of the submit button that was clicked, along with the rest of the form data.

  2. The <button type="submit" name="..." value="...">...</button> element works perfectly in Chrome/Safari/Firefox, but fails in IE7 (as Lèse majesté pointed out in his comment above); if you don't care about IE, that'd be the way to go.

  3. You could also use an <input type="image" /> element, just remember that the browser submits it as two fields: name.x and name.y. Also, you can't set its value, but that shouldn't be a problem if you're only interested in the presence of the field.

elo80ka