I’m trying to adapt your code to work with an array of boxes, but I can’t get the proper index of the box.
let c = [8];
function setup() {
createCanvas(400, 400);
let x = 1;
for (var y = 0; y < 8; y++) {
c = createCheckbox("check" + y);
c.changed(function() {
console.log(`checkbox ${x} is checked: ${this.checked()}`)
})
}
}
function draw() {
background(220);
}
How would I pass the index instead of the x variable?
let c = [];
function setup() {
createCanvas(400, 400);
let x = 1;
for (var y = 0; y < 8; y++) {
c[x] = createCheckbox("check" + y);
c[x].changed(function() {
console.log(`checkbox ${x} is checked: ${this.checked()}`)
})
}
}
function draw() {
background(220);
}
because the for loop is iterating over y but you refer to x
also you need to declare the index (x or y whichever you like) with let instead of var if you want to use it inside the callback function. If you use var, the index will be always 8 because var is always in the global scope. If you use let, every callback will retain the value (I know it’s so weird!)
and in hindsight it helps a lot if you post a complete sketch (I mean not your complete project but a short sketch that runs and describes your problem) so we can give you advice more effectively. If you can give a link to the web editor that would be even better!