I can’t seem to figure this out. It’s working fine for the first section of the for loop, but then the var is lost on the inner click function I commented where it breaks…
Plus, there’s probably a cleaner way to write it to begin with:
$(function () {
var a = "rgb(58,88,90)";
var b = "rgb(123,156,158)";
for (var c = 1; c <= 3; c++) {
if ($("#select" + c).is(":checked")) {
$("#select" + c + "-icon").css("background", a);
var d = document.getElementById("select" + c + "_title").innerHTML;
$("#Selection_" + c).val(d)
} else {
$("#select" + c + "-icon").css("background", b);
$("#Selection_" + c).val("Off")
}
$("#select" + c).click(function () {
// here's where it stops working... var c is no longer recognized...
if ($("#select" + c).is(":checked")) {
$("#select" + c + "-icon").css("background", a);
var d = document.getElementById("select" + c + "_title").innerHTML;
$("#Selection_" + c).val(d)
} else {
$("#select" + c + "-icon").css("background", b);
$("#Selection_" + c).val("Off")
}
})
}
return false });
Here are the first pair of objects it’s targeting:
<label for="select1"><aside id="select1-icon" class="icon-form right rounded"><img src="../common/images/icon-viewDemo.png" /></aside>
<input type="checkbox" id="select1" name="select" checked="checked" class="view" /> <h5 id="select1_title">Watch Demo</h5></label>
And:
<input type="hidden" id="Selection_1" name="Selection_1" value=""/>
You are capturing your loop variable, so when the
forloop is finished, the variablechas the value 4, which is the value the function sees when it executes.This will alert
4because by the time you callx(), the variablechas the value4.If you want to capture the value of
crather than the variable itself, you can give each function a separate copy. I split the handler into a separate local function for readability.You can learn more about this phenomenon on this Web page and in this earlier stackoverflow question.