-1

updateTotal() function not defined, however, i have the function defined inside of $(document).ready( function () { and have called updateTotal() inside of other methods where it needs to be used. Running total not updating. console is showing an updateTotal() not defined. Why could i be getting this error?

$(document).ready( function () {

 $('#plan').on('change', function() {
   var priceText;

   switch(this.value) {
     case 'monthly':
      priceText = '10.00 /mo';
      break;
     case 'quarterly':
      priceText = '$9.00 /mo';
      break;
     case 'yearly':
      priceText = '7.00 /mo';
      break;
   }

   $('#price').text(priceText)
  });

 function updateTotal() {
  var total = 0;

  var entries = $('.entry')

  if (entries.length)
    $('#empty').show();
  else
    $('#empty').hide();

  $('.entry').each( function(index, entry) {
    var data = $(entry).data();
    var price = parseFloat(data.price)
    var installment = data.plan
    switch(installment) {
      case 'monthly':
        total += price;
        break;
      case 'quarterly':
        total += price * 4;
        break;
      case 'yearly':
        total += price * 12;
        break;
    }
  })

  $('#total').text('$' + total);
}
});


$('#add').on('click', function() {
  var plan = $('#plan')
  var installment = plan.val();
  var price = $('#price').text();
  var inCart = $('#in_cart');
  var numeric = price.replace(/[[A-Za-z$\/\s]/g, '');
  var data = 'data-price="' + numeric + '" data-plan="' + 
  installment + '"';
  inCart.append('<li>' + installment + ' - ' + price + '<button 
 class="remove">X</button></li>')
  updateTotal();
});

  $(document).on('click', '.remove', function() {
  $(this).parents('li').remove();
  $('#empty').on('click', function() {
    $('#in_cart').empty();
    updateTotal();
  });

});

Dylan T
  • 139
  • 11
  • 3
    Suggested Duplicate: [What is the scope of variables in javascript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Taplar Jun 18 '19 at 18:05

1 Answers1

2

Functions in JavaScript are scoped in global or function scope, so updateTotal is visible only in document.ready function.

You should try to define updateTotal in global scope (outside document.ready) or create some common scope using IIFE (https://developer.mozilla.org/en-US/docs/Glossary/IIFE) to not to populate global scope too much.

Some info about scoping: https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

  • thanks! error went away after defining function outside of document.ready – Dylan T Jun 18 '19 at 18:24
  • After debugging, I discovered the function did in fact need to be inside document.ready. The inCart.append line was not written properly. Needed an
  • and also needed to append price.
  • – Dylan T Jun 19 '19 at 06:27