Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a hidden field value based on which button is clicked with JavaScript

Tags:

javascript

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.

like image 977
GSto Avatar asked Aug 23 '10 18:08

GSto


2 Answers

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.

like image 78
geowa4 Avatar answered Sep 20 '22 08:09

geowa4


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)"/>
like image 33
Pat Avatar answered Sep 22 '22 08:09

Pat