Chipe
Chipe

Reputation: 4801

How to add numbers in an array, and re-evaluate and add numbers when more are added to array?

I am trying to add numbers in an array and update the DOM with the added numbers. Then when more numbers are added to the array, when the addition function is run again, the array is re-evaluated and the DOM updated with what the numbers add up to in the array.

Here is a fiddle: http://jsfiddle.net/scu67aou/2/

Currently, it is only displaying the last number in the array, and not adding what is in the array. Thanks for any help.

JavaScript:

var numb = [];
var total = '';

$('.new').on('click', function(){
    var infoStuff = $('.to-add input').val();
    $('.added').append('<div class="test">'+ infoStuff + '</div>');
    numb.push(infoStuff);
});

$('.button').on('click', function(){
    for(var i=0; i < numb.length; i++){
        total = Number(numb[i]);
    }
    $('.total').html(total);
});

Upvotes: 0

Views: 94

Answers (2)

bruchowski
bruchowski

Reputation: 5331

Check out this fiddle: http://jsfiddle.net/t8htbo5u/3/

var numb = [];

$('.new').on('click', function(){
        var infoStuff = $('.to-add input').val();
        $('.added').append('<div class="test">'+ infoStuff + '</div>');
        numb.push(parseInt(infoStuff));
});

$('.button').on('click', function(){
    $('.total').html(numb.reduce(function(prev, curr){
        return prev + curr;
    }, 0));
});

I used Array.reduce and ran parseInt on your infoStuff before adding it to numb for the sake of the example, you can change that it you want to take decimals.

Upvotes: 1

T J
T J

Reputation: 43156

You need to add the new values to total inside the loop, rather than assigning the new value to it. Also, declare total as a local variable - otherwise the new numbers will be added to the total of previous calculation:

$('.button').on('click', function () {
  var total=0; // local variable, starts with 0 every time
  for (var i = 0; i < numb.length; i++) {
    total += Number(numb[i]); // add the number to existing total
  }
  $('.total').html(total);
});

Updated Fiddle

Upvotes: 1

Related Questions