I really find it difficult getting to grips with JavaScript's variable scope. It never seems that consistent... probably because I never understand it right. Anyway...
I'm trying to build a simple price calculator. The code is supposed to loop through a bunch of
<select> boxes, send an AJAX query to get the price for the currently selected product, adding that amount onto the total each time, before outputting it into an
<input type="text" /> element further down the page.
Onto the code:
JavaScript Code:
$("#course_calculate").click(function() {
var totalCost = Number(0);
$("#course_dropdown_container select").each(function(i) {
if(this.value != 0) {
$.get("/_cms/admin/ajax/sku_get_price.php", { id: this.value }, function(data) {
totalCost = totalCost + Number(data);
});
}
});
$("#booking_total_cost").attr("value", totalCost.toFixed(2));
});
If I
alert() the value of
totalCost right after a new price has been added, it works as expected. The value of
totalCost, however, doesn't seem to persist beyond the
each() function, and as such, referring to
totalCost at the end of the script just outputs zero.
If anyone could point me in the right direction here I'd be very grateful