-
attaching onClick events to checkboxes with for loop
I have a problem with attaching onClick events to checkboxes.
I wan’t to control light layers using interface. First I collect all lights in array, and then I create UI/pallette with checkboxes for turning lights on/off.
If I do it manually (hard coding) everything works as expected. Here is the example:
checkbox[0].onClick = function() {
light[0].enabled = !light[0].enabled;
}
Checkbox is array of checkboxes (how many lights that many checkboxes), and light is array of all lights in the composition. This works, but the problem is if you have more lights (and you don’t know when scripting how many lights are going to be in the composition).
Possible solution was to attach onClick event to every checkbox using for loop, like this:
for(i=0; i<light.length; i++){
checkbox[i].onClick = function() {
light[i].enabled = !light[i].enabled;
}
}
But the problem is that counter i does not work in the function. After executing the script, and trying to turn on/off lights, function is still using i number (which is number of lights + 1). So in the end, what I get is this (simulation for a scene with 2 lights – counter should be 0 or 1, depending which light you try to turn on/off):
checkbox[2].onClick = function() {
light[2].enabled = !light[2].enabled;
This line of code executes for light1 and also for light 2. And no matter how many lights, number is allways number of lights +1.What am I missing? How come the script works fine when hard coding numbers but it does not when using for loop. Does i counter even enter the function. It seems that instead of actual number, the variable i is used when trying to turn lights on/off.
Thanks,
Goran