-1

There are already a few other posts on SO for this topic, like: Loop through array and return sum of all values. I have used the techniques from there and am still not getting the right result.

I have a UL with Several LI's in it. Each of those LI's has text in them which I need adding to an array, once they have all been added I need to add them up.

JSFIDDLE: http://jsfiddle.net/4Be6N/

Here is the jQuery:

$(document).ready(function() {

var arrTotals = [];
var totalAmount = 0;

$( ".cartprice" ).each(function( index ) {

    arrTotals.push = $(this).text(); 
    console.log(arrTotals);
});

for (var i = 0; i < arrTotals.length; i++) {
    totalAmount += arrTotals[i] << 0;
}

console.log('Total Amount: ' + totalAmount)   

});

However, the console is displaying:

Total Amount: 0

Can anyone see why?

Community
  • 1
  • 1
DannieCoderBoi
  • 728
  • 2
  • 12
  • 31

2 Answers2

1

Use this :

$(document).ready(function() {

    var arrTotals = [];
    var totalAmount = 0;

    $( ".cartprice" ).each(function( index ) {

        arrTotals[index] = $(this).text(); 
        console.log(arrTotals[index]);
        totalAmount+=parseFloat($(this).text());
   });

    console.log('Total Amount: ' + totalAmount)   

});

Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

I think shortest way possible something like this:

$(document).ready(function () {
    var totalAmount = 0;
    $(".cartprice").each(function (index) {
        totalAmount += parseFloat($(this).text());
    });
    console.log('Total Amount: ' + totalAmount);
});
Jai
  • 74,255
  • 12
  • 74
  • 103