28

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?

6 Answers 6

45

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);
    });
Sign up to request clarification or add additional context in comments.

6 Comments

Slightly amusing that you made a huge point about needing to specify the radix, but haven't actually done so in your updated version of his code.
@AnthonyGrist I preferred to show him the solution + a big warning so he will remember it.
This answer is now confusing and unhelpful.
I'm using this code for a mobile web app so I guess it's just webkit I'll need to cover. But thanks for the explanation!
I dont think need to use parseInt because If you want to add decimal inputs then It will give you the correct result. You can use eval instead of parseInt. see the example below
|
8

Use parseFloat() or parseInt()

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

Comments

4

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);

3 Comments

to show him the answer without explaining where is the catch (radix) is not what this site is about. You didnt make him any smarter. You just showed him the answer. greatly educational !
@RoyiNamir The key point is that he needs to convert the string to an integer so it's doing addition and not concatenation. I've also linked him to the MDN documentation for parseInt(), which has its own warnings about specifying the radix, and I included a radix in my answer because it needs to be there.
I'm not arguing with you.we both right. there is no competition here.
0

The javascript function parseInt() should achieve what you require, here's a fiddle: http://jsfiddle.net/k739M/

And some formatted code:

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

    alert(totalPoints);
});​

Additionally, if you were to call $(each) on '.section input', you can reduce the amount of processing time (and code).

var totalPoints = 0;

$('.section input').each(function(){
    totalPoints += parseInt($(this).val());
});

alert(totalPoints);

1 Comment

Calling .each() on the '.section input' selector would completely change the functionality. Additionally, parseInt() is plain JavaScript, not a jQuery function.
0
Use eval instead of parseInt
var a = "1.5";
var b = "2";
var c = parseInt(a) + parseInt(b);
console.log(c); //result 3

var a = "1.5";
var b = "2";
var c = eval(a) + eval(b);
console.log(c); //result 3.5 this is accurate

Comments

0

You can also use reduce() method of Array to get the sum:

var arrayOfValues = $('.section input[type=radio]').map(function(index, input) {
    return parseInt($(input).val());
}).toArray();
var sum = arrayOfValues.reduce(function(val1, val2) {
    return val1 + val2;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.