Yunowork
Yunowork

Reputation: 345

Calculate sum of values

I'm trying to get the sum of some values in jQuery. I do this with

var sum = 0;
$(".total").text(sum += parseInt($(".numbers").text(), 10));

but is is not making a sum. I have tried the following which is also not working?

var sum = 0;
$(".total").parseInt(sum += parseInt($(".numbers").text(), 10));

How can I simply calculate the sum here?

Demo: http://jsfiddle.net/M7ghD/

Upvotes: 1

Views: 169

Answers (4)

Amit
Amit

Reputation: 15387

You can use as also

  var sum = 0;
  $('.numbers').each(function() {
        sum += Number($.text(this));
  });

 $(".total").text(sum);

parseInt(string) will convert a string containing non-numeric characters to a number, as long as the string begins with numeric characters.

Number(string) will return NaN if the string contains any non-numeric characters

DEMO

Upvotes: 0

christian314159
christian314159

Reputation: 639

Try this http://jsfiddle.net/M7ghD/1/:

It seems doing $(".numbers").text() will give you a concatenated string of all your span.numbers at the same time (= '421293'). You have to loop through the elements and sum them up:

var sum = 0;
$('.numbers').each(function(){
  sum += parseInt($(this).text(),10);
});
$(".total").text( sum );

Upvotes: 0

laaposto
laaposto

Reputation: 12213

You have to take each value of class=numbers and sum it.

Try:

var sum = 0;

$( ".numbers" ).each(function() {
  sum=sum+parseInt($(this).text(), 10)
})

$(".total").text(sum);

DEMO

Upvotes: 1

VisioN
VisioN

Reputation: 145478

To sum values you need to iterate .numbers elements:

var sum = 0;
$('.numbers').each(function() {
    sum += parseInt($.text(this), 10);
});

$('.total').text(sum);

DEMO: http://jsfiddle.net/M7ghD/5/

Upvotes: 2

Related Questions