In my sample code, I have 2 dropdownlists (but in the real code the number varies because the dropdownlists are created dynamically) and what I wanted to do is to count how many dropdownlists are selected with a non-zero value. I used closure to keep track of the total number of dropdownlists with non-zero selected value. I was successful in doing that (refer to http://jsfiddle.net/annelagang/scxNp/9/).
Old/Working Code
$("select[id*='ComboBox']").each(
function() {
$(this).change(
function() {
compute(this);
});
});
var compute = (function () {
var total = 11;
var selectedDdl = [];
$("#total").text(total);
return function (ctrl) {
var id = $(ctrl).attr("id");
var ddlMeal = document.getElementById(id);
var found = jQuery.inArray(id, selectedDdl);
if (ddlMeal.options[ddlMeal.selectedIndex].value != 0){
if(found == -1){
total += 1;
selectedDdl.push(id);
}
else{
total = total;
}
}
else {
total -= 1;
var valueToRemove = id;
selectedDdl = $.grep(selectedDdl, function(val)
{ return val != valueToRemove; });
}
$("#total").text(total);
};
}());
Note: I initialized the total variable with 11 because as I mentioned in the real code I can have more than 2 dropdownlists and I just wanted to test if my code will work on values more than 2.
When I tried transferring the closure inside the .change() event, it no longer works (see http://jsfiddle.net/annelagang/scxNp/12/) Could somebody please help me figure this one out? I've been doing this code for a few days now and it's getting quite frustrating.
New/Non-working code:
$("select[id*='ComboBox']").each(
function() {
$(this).change(
function() {
(function () {
var total = 11;
var selectedDdl = [];
$("#total").text(total);
return function (ctrl) {
var id = $(ctrl).attr("id");
var ddlMeal = document.getElementById(id);
var found = jQuery.inArray(id, selectedDdl);
if (ddlMeal.options[ddlMeal.selectedIndex].value != 0){
if(found == -1){
total += 1;
selectedDdl.push(id);
}
else{
total = total;
}
}
else {
total -= 1;
var valueToRemove = id;
selectedDdl = $.grep(selectedDdl, function(val)
{ return val != valueToRemove; });
}
$("#total").text(total);
};
}());
});
});
Thanks in advance.
P.S. I'm also open to less messier solutions.