我的頁面由幾個輸入組成,名爲「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