0

The below script is giving the error - ReferenceError: cat is not defined. I'm missing something simple I know!

// calculate the sum of each table
$(calculateSum);

function calculateSum() {
    var sum = 0;
    // iterate through each td based on class and add the values
    $.each(['income', 'expenses', 'bills', 'savings', 'debt'], function(index, cat) {

        var value = $('#'+cat+' .amount').text();
        // add only if the value is number
        if(!isNaN(value) && value.length != 0) {
            sum += parseFloat(value);
        }
    });
$('#'+cat+' .total').text('$'+ sum); 
};
4
  • is cat declared anywhere within the scope your trying to use it?.... Feb 4, 2014 at 11:37
  • cat is not defined in teh scope of calculateSum it is available only inside the each callback Feb 4, 2014 at 11:37
  • 2
    $('#'+cat+' .total').text('$'+ sum); Can't find cat outside the $.each loop.
    – msapkal
    Feb 4, 2014 at 11:37
  • can you share the target html Feb 4, 2014 at 11:39

2 Answers 2

2

cat is the argument to the function you're passing into $.each, so it doesn't exist outside that function. Either you need to move the $('#'+cat+' .total').text('$'+ sum); line into the function, or do something else entirely.


Note that your code combines the values for various different categories (income, expenses, etc.) in a single sum variable. The whole logic of the code shown looks a bit suspect, you may want to step back and look at it in the broader context of what you're trying to do.

1
  • I understand what you mean. Just not sure how to implement it
    – user537137
    Feb 4, 2014 at 11:45
0

Move this

$('#'+cat+' .total').text('$'+ sum); 

iniside

$.each()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.