标记:
<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>
我想在formOne中单击按钮时更改formTwo中隐藏字段的值。我希望通过使用简单的JavaScript(而不是JQuery)并且不向输入添加ID(仅通过它们的名称)来完成此操作。
我尝试过这个JavaScript函数:
function change(field) {
alert(field.value);
}
如果我将隐藏的输入移动到formOne,它会输出正确的值。修改该函数以在formTwo中输出隐藏字段的值的最简单方法是什么?
我也试过了,但没有工作:
function change(field) {
alert(document.forms[formTwo].field.value);
}
我想要做一些简单的事情。有可能吗?
答案 0 :(得分:0)
<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>
你首先错过了一个结束“)”。其次,您需要一个Javascript来处理用户的操作(此代码应放在</html>
标记之前)。
<script>
function change(element)
{
document.getElementsByName(element)[0].value = "other_value";
}
</script>
(这假定myHiddenField
是具有此name属性的第一个或唯一元素。)
就是这样。
答案 1 :(得分:0)
经过测试,我发现只有隐藏的输入在formOne中时,上述答案才有效。最后我找到了一个解决方案,我在这里找到了它:http://www.w3schools.com/jsref/coll_doc_forms.asp。
function change(index)
{
document.forms['formTwo'].item(index).value = "other_value";
}