【发布时间】:2017-10-28 17:05:30
【问题描述】:
我的页面由多个表单组成,其中包含多个名为“values[]”的输入。 在其中一种形式中修改这些输入时,我想对这些值求和并将结果显示在另一个名为“total”的相同形式的输入中。
我的 html 代码如下所示:
<form action="index.php" method="post" id="form_1">
<input type="text" name="values[]" id="value_1_1" onkeyup="sum_values(this)" />
<input type="text" name="values[]" id="value_1_2" onkeyup="sum_values(this)" />
[... More inputs with the name "values[]" ]
<input type="text" name="total" disabled>
</form>
<form action="index.php" method="post" id="form_2">
<input type="text" name="values[]" id="value_2_1" onkeyup="sum_values(this)" />
<input type="text" name="values[]" id="value_2_2" onkeyup="sum_values(this)" />
[... More inputs with the name "values[]" ]
<input type="text" name="total" disabled>
</form>
我的 javascript 是:
<script type="text/javascript">
function sum_values(x){
var arr = document.getElementById(x.form.id).elements['values[]'];
var tot=0;
for(var i=0;i<arr.length;i++)
{
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById(x.form.id).elements['total'].value = tot;
}
</script>
我很高兴终于看到第一个表单工作了,但后来我发现第二个表单不行......
你能帮我理解为什么吗? 我是 javascript 的初学者,我试图安排一些我找到的代码。 非常感谢
【问题讨论】:
-
不应该是
var arr = document.getElementById(x.form.id).value -
如果我是正确的,“x.form.id”给出了整个表单的 id。您引用的行应该在此表单(而不是整个表单)中获取名称为“values []”的输入。
-
然后使用
x.id代替x.form.id,这肯定会工作
标签: javascript forms input sum