Amanda Sky
Amanda Sky

Reputation: 161

Jquery using map to sum array

My values array is returning correctly in the form of [100,200,300,500] I just wish to sum up these values, what am I doing wrong?

Jquery

$('select').focus(function () {
    previous = parseInt($(this).val());
}).change(function() {

    var item_cost = parseInt($(this).attr('cost'));
    
    values = $.map($('select[name="cookies"]'), function (e) {
            
        return $(e).val()* item_cost;
                     
        for (var i = 0; i < values.length; i++) {
            total += parseInt(values[i]);
            console.log(total);                              
        }
    });

    alert(values);

Upvotes: 0

Views: 1606

Answers (1)

Joe
Joe

Reputation: 82604

Your code needs formatting. You missed a closing }); You need to declare var total = 0; as well. I'm not sure if that is elsewhere in your code.

$('select').focus(function() {
    previous = parseInt($(this).val());
}).change(function() {
    var item_cost = parseInt($(this).attr('cost'));

    values = $.map($('select[name="cookies"]'), function(e) {
        return $(e).val() * item_cost;
    }); // <-- RIGHT THERE

    for (var i = 0; i < values.length; i++) {
        total += parseInt(values[i]);
        console.log(total);
    }
});
alert(values);​

Upvotes: 2

Related Questions