Vince February 2016

Javascript: How to Dynamically Update My Closure?

I am very new to JS so, apologies if this is a dumb question:

Objective: Each time the user selects a car from the drop down menu the price of the car increments a running total.

I have a JSFiddle of the code here: Update a Closure

  <select id="select">
  <option value="">Select</option>
  <option value="100.00">Volvo</option>
  <option value="200.00">Saab</option>
  <option value="300.00">Mercedes</option>
  <option value="400.00">Audi</option>
</select>

<p>total:</p>
<p id="total"> </p>

Javascript:

var addTo = function(passed) {

  var add = function(inner) {
    return parseInt(passed) + parseInt(inner);
  }

  return add
};

var inner = 0; // Need to Dynamically be able to Update this value so that it increments with each new car selected

var addProd = new addTo(inner);

$("#select").change(function() {
  var car = $("#select").val();

  $("#total").append(addProd(car));
});

So, I grab the selected product. The closure then adds the product price to zero to start.

I select another car. This second car price must be added to the first, thus incrementing the total. It is the total which is displayed on the webpage.

Sounds like it should be easy. The code in the Fiddle does not work. I do not know how to get the code to increment the "inner" value of the closure. Obviously it is the inner which must persist between each selection.

Answers


Scott Schwalbe February 2016

I think this situation would best use an IFFE

var carTotal = (function() {
  var total = 0;

  return {
    addToTotal: function(val) {
      total += val;
      return total;
    }
  };
})();

$("#select").change(function() {
  var car = $("#select").val();

  $("#total").append(carTotal.addToTotal(car));
});


Barmar February 2016

You need a variable inside the closure to hold the running total.

var addTo = function(passed) {
  var total = parseInt(passed);
  var add = function(inner) {
    total += parseInt(inner);
    return total;
  }

  return add;
};


mkaatman February 2016

I think this is what you're looking for.

var runningTotal = 0;

$("#select").on('change', function() {
  var car = parseInt($(this).val());
  runningTotal += car;

  $("#total").html(runningTotal);
});

Post Status

Asked in February 2016
Viewed 1,755 times
Voted 11
Answered 3 times

Search




Leave an answer