Update the value of a variable

When "Add to Cart" is clicked, the value is added to ".total-cart", and after an option is chosen in , the option value is added to the total cart value and displayed in ". total-all ". But when you click "Add to cart" again, the value of ".total-all" does not change. It is only updated when another option is selected within . Is there a way to update the value of ".total-all" automatically?

‚óŹ DEMO

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script> //Select with Fees
        $(document).ready(function() {
       var sheetURL =
         "https://spreadsheets.google.com/feeds/list/1lyCo_s17CxGzI2n83_H2IKTTE-ot9Pam1ZyC8t6qZmE/2/public/values?alt=json";
       $.getJSON(sheetURL, function(data) {
         var entryData = data.feed.entry;
         console.log(data);
         jQuery.each(entryData, function() {
           $("#selectID").append(
           
      '<option  hidden="hidden" selected="selected"  value="0">Choose</option><option value="' + this.gsx$price.$t.replace(/,/, '.') +  '">' + this.gsx$name.$t + '&nbsp;&nbsp;&nbsp;$ ' + this.gsx$price.$t + '</option>'
      
           );
         });
       });
      });
     </script>
     
     
     
     <script>
        var shoppingCart = (function() {
    
          cart = [];
          
          // Constructor
          function Item(name, price, count) {
            this.name = name;
            this.price = price;
            this.count = count;
          }
          
          var obj = {};
          
          // Add to cart
          obj.addItemToCart = function(name, price, count) {
            for(var item in cart) {
              if(cart[item].name === name) {
                cart[item].count ++;
        
                return;
              }
            }
            var item = new Item(name, price, count);
            cart.push(item);
            
          }
        
          // Total cart
          obj.totalCart = function() {
            var totalCart = 0;
            for(var item in cart) {
              totalCart += cart[item].price * cart[item].count;
            }
            return Number(totalCart.toFixed(2));
          }
        
          return obj;
        })();
        
        
        $(document).ready(function() {
           
            var sheetURL4 = "https://spreadsheets.google.com/feeds/list/1lyCo_s17CxGzI2n83_H2IKTTE-ot9Pam1ZyC8t6qZmE/1/public/values?alt=json";
 

 $.getJSON(sheetURL4, function(data4) {
   var entryData4 = data4.feed.entry;
   console.log(data4);
   jQuery.each(entryData4, function() {
     $("#content").append(
       
    this.gsx$name.$t + '<br> $&nbsp;' + this.gsx$price.$t +'<br><a href="#" data-name=" ' + this.gsx$name.$t + ' " data-price=" ' + this.gsx$price.$t +'"class="add-to-cart btn btn-primary">Add to cart</a><br>'
     
     );
   });  
});



$.getJSON(sheetURL4, function(data4) {
$('.add-to-cart').click(function(event) {
            event.preventDefault();
            var name = $(this).data('name');
            var price = +$(this).data('price').replace(/,/, '.');
            console.log(price);
            // console.log($(this).data('price'));
            shoppingCart.addItemToCart(name, price, 1);
            displayCart();
          });
        

});

});
          
        function displayCart() {
          
        
          var total = shoppingCart.totalCart();

        

                $("#selectID").change(function() {
                    var totalWithTax = $(this).val();
                    $('.total-tax').html(totalWithTax);

                    var sumTotalAll = total + +totalWithTax;

                    $('.total-all').html(sumTotalAll.toFixed(2));
                    
                });
                
          
          $('.total-cart').html(total.toFixed(2));
          
        
        }
        

        displayCart();
        
        
        
     </script>
   
<div id="content"></div>
     <br>
        <select id="selectID" style="width:200px" value="0"></select>
        


        <p>Subtotal: &nbsp;$ <span class="total-cart"></span></p>   
        <p>Tax Value: &nbsp;$ <span class="total-tax"></span></p>
        <p><strong>Total: &nbsp;$ <span class="total-all"></span></strong></p>

3 thoughts on “Update the value of a variable”

  1. You can call your change event on select-box whenever any item is added to cart using $("#selectID").trigger('change') so that total value will get updated .

    Demo Code:

    var shoppingCart = (function() {
    
      cart = [];
    
      // Constructor
      function Item(name, price, count) {
        this.name = name;
        this.price = price;
        this.count = count;
      }
    
      var obj = {};
    
      // Add to cart
      obj.addItemToCart = function(name, price, count) {
        for (var item in cart) {
          if (cart[item].name === name) {
            cart[item].count++;
            return;
          }
        }
        var item = new Item(name, price, count);
        cart.push(item);
      }
      // Total cart
      obj.totalCart = function() {
        var totalCart = 0;
        for (var item in cart) {
          totalCart += cart[item].price * cart[item].count;
        }
        return Number(totalCart.toFixed(2));
      }
    
      return obj;
    })();
    
    $(document).on('click', '.add-to-cart', function(event) {
      event.preventDefault();
      var name = $(this).data('name');
      var price = +$(this).data('price').replace(/,/, '.');
      shoppingCart.addItemToCart(name, price, 1);
      $("#selectID").trigger('change') //call select
    });
    //use like this because select-box are dynamically created
    $(document).on('change', '#selectID', function() {
      var total = shoppingCart.totalCart();
      var totalWithTax = $(this).val();
      $('.total-tax').html(totalWithTax);
      var sumTotalAll = total + +totalWithTax;
      $('.total-all').html(sumTotalAll.toFixed(2));
      $('.total-cart').html(total.toFixed(2));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="content">item 1<br> $&nbsp;10<br><a href="#" data-name=" item 1 " data-price=" 10" class="add-to-cart btn btn-primary">Add to cart</a><br>item 2<br> $&nbsp;20<br><a href="#" data-name=" item 2 " data-price=" 20" class="add-to-cart btn btn-primary">Add to cart</a><br>item
      3
      <br> $&nbsp;30<br><a href="#" data-name=" item 3 " data-price=" 30" class="add-to-cart btn btn-primary">Add to cart</a><br></div>
    <br>
    <select id="selectID" style="width:200px" value="0">
      <option hidden="hidden" selected="selected" value="0">Choose</option>
      <option value="1">tax 1&nbsp;&nbsp;&nbsp;$ 1</option>
      <option hidden="hidden" selected="selected" value="0">Choose</option>
      <option value="2">tax 2&nbsp;&nbsp;&nbsp;$ 2</option>
      <option hidden="hidden" selected="selected" value="0">Choose</option>
      <option value="3">tax 3&nbsp;&nbsp;&nbsp;$ 3</option>
    </select>
    
    
    
    <p>Subtotal: &nbsp;$ <span class="total-cart"></span></p>
    <p>Tax Value: &nbsp;$ <span class="total-tax"></span></p>
    <p><strong>Total: &nbsp;$ <span class="total-all"></span></strong></p>
    Reply
  2. Try this –

    $.getJSON(sheetURL4, function (data4) {
        $('.add-to-cart').click(function (event) {
            ...
            shoppingCart.addItemToCart(name, price, 1);
            $('.total-all').html((shoppingCart.totalCart() + Number($("#selectID").val())).toFixed(2)); // add this, it will update total amount
            displayCart();
        });
    });
    
    Reply

Leave a Comment