Reputation: 345
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
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
Upvotes: 0
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
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);
Upvotes: 1
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