-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?

1
  • arrTotals.push($(this).text()); works fine Commented Jun 9, 2014 at 9:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Can you help me with something else. When I add $('#thetotal').text(newTotalAmount); the result is NaN ?
Yes why not, but you have variable totalAmount and where is newTotalAmount?
please share your code on jsfiddle so that i can help you better.
When I add it in JSFiddle it works: jsfiddle.net/4Be6N/9 but not on the website :/
check for console error. for more information webmasters.stackexchange.com/questions/8525/…
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);
});

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.