我知道這種性質的問題在很多場合都被問過,但是在幾個小時嘗試不同的東西之後,我仍然沒有更聰明的想法。希望有人能夠啓發我。用jQuery計算多個輸入的總和
我正在嘗試添加多個輸入的值並將總值輸出到單獨的字段中。下面的代碼片段完成了這項工作,但我需要循環每個季節,因爲它們是使用不同的ID動態創建的。
$('#season-0 .appearances').val(
Number($('#season-4 .appearances').val()) +
Number($('#season-36 .appearances').val())
);
$('#season-0 .goals').val(
Number($('#season-4 .goals').val()) +
Number($('#season-36 .goals').val())
);
我已經嘗試了一些不同的功能,但似乎沒有奏效,例如:
var sum = 0;
$('.appearances').each(function(){
sum = sum + Number($(this).val());
});
$('#season-0 .appearances').html(sum);
我會很感激有這方面的幫助,它一直在做我的頭在太長今;)
下面是相關的HTML:
<div id="season-0">
<table>
<tr>
<td>
<input type="text" data-index="appearances" class="appearances" value="" />
</td>
<td>
<input type="text" data-index="goals" class="goals" value="" />
</td>
</tr>
</table>
</div>
<div id="season-4">
<table>
<tr>
<td>
<input type="text" data-index="appearances" class="appearances" value="25" />
</td>
<td>
<input type="text" data-index="goals" class="goals" value="4" />
</td>
</tr>
</table>
</div>
<div id="season-36">
<table>
<tr>
<td>
<input type="text" data-index="appearances" class="appearances" value="19" />
</td>
<td>
<input type="text" data-index="goals" class="goals" value="8" />
</td>
</tr>
</table>
</div>
什麼是你的代表HTML? –
我編輯了我的文章,包括HTML,感謝您的時間。 – roofdog