Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery sum of input values in sections

I'm trying to find the sum of input values within multiple sections. I've put my code so far below.

The HTML:

<div class="section">
  <input type="radio" name="q1" value="2"/>
  <input type="radio" name="q2" value="0"/>
  <input type="radio" name="q3" value="1"/>
  <input type="radio" name="q4" value="3"/>
</div>

The jQuery:

$('.section').each(function(){
  var totalPoints = 0;
  $(this).find('input').each(function(){
    totalPoints += $(this).val();
  });
  alert(totalPoints);
});

Please note this is a simplified version of the code I'm actually using. So I want this to alert 2 values (the sum of each section): 8 then 6. Instead I'm just getting a string of all the values. So the first section alerts 0143.

Any ideas how I get a cumulative sum instead of a string?

like image 675
CaribouCode Avatar asked Jan 03 '13 15:01

CaribouCode


3 Answers

You are doing "1"+"1" and expect it to be 2 ( int)

it is not.

a very quick (and not fully correct) solution is :

$('.section').each(function(){
  var totalPoints = 0;
  $(this).find('input').each(function(){
    totalPoints += parseInt($(this).val()); //<==== a catch  in here !! read below
  });
  alert(totalPoints);
});

catch ? why ?

answer: You should always use radix cause if you dont , a leading zero is octal !

 parseInt("010") //8 ( ff)
 parseInt("010") //10 ( chrome)


 parseInt("010",10) //10 ( ff)
 parseInt("010",10) //10 ( chrome)

well.... you get the idea. supply radix !

edit

final solution (using .each( function(index, Element) ))

$('.section').each(function(){
      var totalPoints = 0;
      $(this).find('input').each(function(i,n){
        totalPoints += parseInt($(n).val(),10); 
      });
      alert(totalPoints);
    });
like image 177
Royi Namir Avatar answered Sep 22 '22 21:09

Royi Namir


Use parseFloat() or parseInt()

var totalPoints = 0;
$('.section input').each(function(){
        totalPoints = parseFloat($(this).val()) + totalPoints;
});
alert(totalPoints);
like image 35
Doguhan Okumus Avatar answered Sep 24 '22 21:09

Doguhan Okumus


The value is stored as a string, so calling += is doing string concatenation. You want/need to treat it as a number, so it does addition. Use the parseInt() function to convert it to a number:

totalPoints += parseInt($(this).val(), 10);
like image 28
Anthony Grist Avatar answered Sep 23 '22 21:09

Anthony Grist