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
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')"/>
use Prototype :-)
But in all seriousness:
id
to the hidden fieldBefore 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";
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.
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)"/>
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.
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.
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.