开发者

Copy value of one form into the hidden field of a second form

I have a page with multiple forms, however all forms need to take the value of a radio button in the products form. Below is a simplified version of my forms which are all on the same page.

<form name="products" method="post" action="" />
<input id="prod_name" name="prod_name" type="radio" value="Product 1" checked />
<input id="prod_name" name="prod_name" type="radio" value="Product 2" />
</form>

<form name="delivery_method1" method="post" action="" />
<input type="hidden" id="item_name" name="item_name" value=""/>
<input type="image" name="submit" value="submit">
</form>

<form name="delivery_method2" method="post" action="" />
<input type="hidden" id="item_name" name="item_name" value=""/>
<input type="image" name="submit" value="submit">
</form>

I understand I should be able to copy the value of "prod_name" into the hidden field of "item_name" using JavaScript however I have tried a number of solutions but they haven't worked.

I have very little JavaScr开发者_Python百科ipt knowledge so I would appreciate if someone could provide me with a full function and details of how the function is actioned from within the form.


ID attributes should be unique. If you don't need them, remove these. If you're using id=... for styling purposes, replace all occurences of id= by class=, and replace the sharp (#) in the CSS by a dot.

When a form is submitted, only elements with a name attribute are sent.
This should work:

....
<script>
function fill(value) {
    var forms = document.forms;
    for (var i = 0; i < forms.length; i++) {
        if (forms[i].item_name) forms[i].item_name.value = value;
    }
}
</script>
</head>
<body>
...
<form name="products" method="post" action="">
<input onchange="fill(this.value)" name="prod_name" type="radio" value="Product 1" checked />
<input onchange="fill(this.value)" name="prod_name" type="radio" value="Product 2" />
</form>
...

All form elements are accessible through their name at the form element. All forms are accessible (by name or by their index in the document) through the document.forms object.

When the radio selection changes, function fill() is called, passing this.value as an argument. From the context of the radio input elements, this.value points to the value of the radio element.

Then, we loop through all forms in the document. If item_name is an element in the form, the value is updated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜