简体   繁体   中英

Click button in form 1: change value of hidden input in form 2 (pure javascript)

Markup:

<form action="index.php" method="post" name="formOne">
    <input type="button" value="Test" onClick="change('myHiddenField')">
    <input type="submit" value="Submit">
</form>

<form action="index.php" method="post" name="formTwo">
    <input name="myHiddenField" type="hidden" value="test">
</form>

I want to change the value of the hidden field in formTwo when clicking the button in formOne. I want this done by using just simple JavaScript (not JQuery) and without adding IDs to the inputs (just by the name of them.)

I have tried this JavaScript function:

function change(field) {
    alert(field.value);
}

And if I move the hidden input to formOne it outputs the correct value. What is the simplest possible way to modify that function to output the value of the hidden field in formTwo?

I also tried this, but not working:

function change(field) {
    alert(document.forms[formTwo].field.value);
}

And I would like something that simple to do the task. Is it possible?

<form action="index.php" method="post" name="formOne">
    <input type="button" value="Test" onClick="change('myHiddenField')">
    <input type="submit" value="Submit">
</form>

<form action="index.php" method="post" name="formTwo">
    <input name="myHiddenField" type="hidden" value="test">
</form>

You're missing a closing ")" first of all. Secondly you'll need a Javascript to deal with the user's action (this code should be placed before </html> tag).

<script>
   function change(element)
     {
       document.getElementsByName(element)[0].value = "other_value";
     }
</script>

(This assumes myHiddenField is the first or only element with this name property.)

That's all.

After testing I found that above answer also only worked if the hidden input was in formOne. Finally I have found a solution though, and I found it here: http://www.w3schools.com/jsref/coll_doc_forms.asp .

function change(index)
{
    document.forms['formTwo'].item(index).value = "other_value";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM