我的页面由几个输入组成,名为“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初学者,我试图安排一些我找到的代码。 非常感谢您
它不应该是'变种ARR =的document.getElementById(x.form.id).value' – wrangler
如果我是正确的, “x.form.id” 给出了整个表单的ID。您所接受的这一行应该在此表单(而不是整个表单)内使用名称“values []”获取输入。 – Corlin
然后用'x.id'代替'x.form.id',这肯定会起作用 – wrangler