0
如何求和多個文本輸入的值?根據現場輸入計算總和
當前總和不正確,因爲它不斷記住和總結之前輸入字段中的先前值。
我有以下代碼:
HTML:
<div class="form-group">
<legend>Risicopotentieel</legend>
<label for="email">Email address:</label>
<select class="selectpicker" id="selectpicker1">
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
<option value="4">text4</option>
</select>
<label for="email">Email address:</label>
<select class="selectpicker" id="selectpicker2">
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
<option value="4">text4</option>
</select>
<label for="email">Email address:</label>
<select class="selectpicker" id="selectpicker3">
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
<option value="4">text4</option>
</select>
</div>
<div class="form-group">
<legend>Score</legend>
<label for="email"> </label>
<input type="text" class="form-control" id="scorefield1">
<label for="email"> </label>
<input type="text" class="form-control" id="scorefield2">
<label for="email"> </label>
<input type="text" class="form-control" id="scorefield3">
<label for="email">Totaalscore</label>
<input type="text" class="form-control" name="riskpottotalscore" id="riskpottotalscore">
</div>
jQuery代碼首先複製所選擇的選項的輸入字段的值。這工作正常。此後,我想計算總和,那是錯誤的。可變totalPoints保持記憶的成績,但我只是想對那些在得分字段1,2和3實際選擇的值來計算的總和:
scorefieldrisk: function(){
totalPoints = 0;
for (var i = 1; i <= 7; i++) {
(function (i) {
$('select[id$="selectpicker' + i + '"]').on("change", function() {
document.getElementById('scorefield'+i).value = this.value;
if(!isNaN(this.value) && this.value.length!=0) {
totalPoints +=(parseInt(this.value));
document.getElementById('riskpottotalscore').value = totalPoints;
}
});
})(i);
}
},