2017-10-28 164 views
0

我的頁面由幾個輸入組成,名爲「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初學者,我試圖安排一些我找到的代碼。 非常感謝您

+0

它不應該是'變種ARR =的document.getElementById(x.form.id).value' – wrangler

+0

如果我是正確的, 「x.form.id」 給出了整個表單的ID。您所接受的這一行應該在此表單(而不是整個表單)內使用名稱「values []」獲取輸入。 – Corlin

+0

然後用'x.id'代替'x.form.id',這肯定會起作用 – wrangler

回答

0

如果您想要獲取特定表單中的所有元素,可以使用類似於以下內容的代碼。除了最終結果輸入選擇器之外,其餘代碼應該可以正常工作。

var formId = 'form1'; 
 
var arr = document.querySelectorAll('#' + formId + ' [name="values[]"]'); 
 

 
var tot=0; 
 
for(var i=0; i<arr.length; i++) { 
 
    if(parseInt(arr[i].value)) 
 
    tot += parseInt(arr[i].value); 
 
} 
 
document.querySelector('#' + formId + ' [name="total"]').value = tot;
<form id="form1"> 
 
    <input type="text" name="values[]" value="5" /> 
 
    <input type="text" name="values[]" value="1" /> 
 
    <input type="text" name="values[]" value="6" /> 
 
    <input type="text" name="values[]" value="8" /> 
 
    <input type="text" name="values[]" value="2" /> 
 
    <input type="text" name="values[]" value="0" /> 
 
    <input type="text" name="values[]" value="1" /> 
 
    <input type="text" name="values[]" value="3" /> 
 
    <input type="text" name="total" disabled> 
 
</form>

+0

這很完美,我只需要用x.form.id替換'form1'。我不知道這種方式來訪問輸入。非常感謝你 ! – Corlin