如何对多个文本输入的值求和?
目前,总和不正确,因为它不断记住和总结之前输入字段中的先前值。
我有以下代码:
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);
}
},