Javascript Question

How to get sum of multiple fields that have same class and get the value of each summation using Javascript

Okay so i have a loop dynamic input field class but i will show how it look likes.

the output is like this

<input type="text" class="sp_criteria1">
value -> 20

<input type="text" class="sp_criteria1">
value -> 25

i need the sum of this ^ = 45

<input type="text" class="sp_criteria3">
value -> 20

<input type="text" class="sp_criteria3">
value -> 25

i need the sum of this ^ = 45

<input type="text" class="sp_criteria5">
value -> 20

<input type="text" class="sp_criteria5">
value -> 25

i need the sum of this ^ = 45

<input type="text" class="sp_criteria6">
value -> 20

<input type="text" class="sp_criteria6">
value -> 25

<input type="text" class="sp_criteria6">
value -> 20

i need the sum of this ^ = 65

is use this

var sum =0;
for(var i=0; i<count_criteria; i++){

$('input.sp_criteria'+i+'').each(function(i, selected){
sum += parseFloat($(selected).val() || 0);
console.log(sum+'sum');
});

}
if(parseFloat(sum) >= 99.00 && parseFloat(sum) <= 100.09){



}else{
if(parseFloat(sum) >= 100.9){
alert('Criteria score Percent must be approximately 100. Your Score Inputed is:'+sum);
return false;
}else if(parseFloat(sum) <= 99.00){
alert('Criteria score Percent must be approximately 100. Your Score Inputed is only:'+sum);
return false;
}

}


but its only add all the values at the same that total is 200

** What i need is to get those sum at the same time 45 45 45 65**

Answer

If you want the individual sums to be output separately then you need to add each one to an array or object within the outer loop:

var result = [];
var count_criteria = 7;
var sum;
var inputs;
for(var i=0; i<count_criteria; i++){
  sum = 0;
  inputs = $('input.sp_criteria'+i);
  if (inputs.length === 0)
    continue;
  inputs.each(function(){
    sum += parseFloat($(this).val()) || 0;
  });
  result.push(sum);
}

console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="sp_criteria1" value="20">
<input type="text" class="sp_criteria1" value="25">
<br>
<input type="text" class="sp_criteria3" value="20">
<input type="text" class="sp_criteria3" value="25">
<br>
<input type="text" class="sp_criteria5" value="20">
<input type="text" class="sp_criteria5" value="25">
<br>
<input type="text" class="sp_criteria6" value="20">
<input type="text" class="sp_criteria6" value="25">
<input type="text" class="sp_criteria6" value="20">

Note that your function loops through all the numbers from 0 to count_criteria, but your sample html doesn't have corresponding inputs for some of those numbers, so I've put in if (inputs.length === 0) continue; to skip ignore those indexes. If you'd rather they output a sum of 0 in the array then just delete that if.

Note also that the || 0 you had with parseFloat() should be after the function, so that if parsing fails it defaults to 0.

Comments