I have DOM-objects that are numbered from 1-10 as so: checkbox_1, back_arrow_1, checkbox_2, back_arrow_2. When the arrow is clicked, I want it to perform the click function of the checkbox-object with same name, for instance
back_arrow_1 clicked
-> $(checkbox_1).click();
I am dynamically binding the click functions for the back_arrow's as so:
(function(){
for (var ar_num = 1; ar_num < 4; ar_num++){
$("back_arrow_"+ar_num).bind("click", function () {
$("checkbox_"+ar_num).click();
});
}
})();
And console.logging() shows that it does bind the correct arrow, but when I click any of the arrows, it does the click function for the checkbox_4, which is because I assume that instead of bind the "checkbox_1" for example, the browser performs the event of checkbox_+ar_num, getting the number that the for loop left ar_num at.
What would be the correct way to perform this functionality?
You need to set a closure, that will save the value of ar_num after your loop is over in your click function.
Look at this : jsfiddle
for (var ar_num = 1; ar_num < 4; ar_num++){
(function(num) {
$("#back_arrow_"+num).bind("click", function () {
$("#checkbox_"+num).click();
});
})(ar_num);
}