Steve
Steve

Reputation: 14912

Adding numbers to running total in jquery loop

I have a variable that is supposed to hold a running total. On each pass of this loop, and amount should be added to the running total. I must be missing something, since I get either undefined or NaN.

$('#btnSubmit').click(function(e) {
    var totalSqft;
    $('.fieldset').each(function() {
        var sqft;
        var width = $(this).find('input:eq(0)').val();
        var height = $(this).find('input:eq(1)').val();
        var type = $(this).find('select').val();
        if (type == 'tri') {
            sqft = (width * height) / 2;
        } else {
            sqft = (width * height);
        };
        totalSqft += sqft;
        alert('this ' + type + ' is ' + width + ' wide and ' + height + ' high, for a total of ' + sqft + ' square feet');
    });
    alert('Done.  Total Sq Ft is ' + totalSqft);
})​

Upvotes: 2

Views: 2119

Answers (1)

Mark Reed
Mark Reed

Reputation: 95242

You need to initialize the value to 0:

var totalSqft = 0;

Otherwise, it gets initialized to undefined, and undefined + a number is NaN.

Upvotes: 7

Related Questions