user2237168 user2237168 - 5 months ago 33
jQuery Question

Calculate sum based on field inputs

How can I sum the values of multiple text inputs?

Currently the sum is not correct as it keeps on remembering and summing previous values that were in the input fields before.

I have the following code:

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">&nbsp;&nbsp;</label>
<input type="text" class="form-control" id="scorefield1">
<label for="email">&nbsp;&nbsp;</label>
<input type="text" class="form-control" id="scorefield2">
<label for="email">&nbsp;&nbsp;</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>


The jQuery code first copies the value of the selected option to an input field. This works fine. Thereafter, I want to calculate the sum and that is were it goes wrong. The variable totalPoints keeps remembering its scores, but I only want to calculate the sum over the values that are actually selected in score field 1, 2 and 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);
}
},

Answer

You should redo the sum from zero each time.

Your code could be simplified to have just one function as handler for all select elements. Also you can use the unitary + operator to convert the string value to number:

$('.selectpicker').on('change', function() {
    totalPoints = 0;
    $('.selectpicker').each(function() {
        totalPoints += +this.value;
    });
    $('#riskpottotalscore').val(totalPoints);
});