Checkbox listener index

I have an array of checkboxes and I need to know which checkbox was pressed. My code looks like this:

uiToogles() {
    var y = 0;
    checkbox = [8];
    for (var x = 0; x < 8; x++) {
      y = x * 20;
      checkbox[x] = createCheckbox(names[x], true);
      checkbox[x].changed(this.myCheckedEvent);
      checkbox[x].position(this.sizex + this.posx + 4, this.posy + y + 12);
    }
  }

  myCheckedEvent() {
    if (this.checked()) {
      console.log("Checking!"); 
    } else {
      console.log("Unchecking!");
    }
  }

Thanks a lot!

hi! one way of achieving this is to bind values to a function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

but this is not really intuitive at first. I recommend using anonymous function like

checkbox[x].changed(function () {
  console.log(`checkbox ${x} is checked: ${this.checked()}`)
})

https://editor.p5js.org/micuat/sketches/bXhblYmdf

note that function(){} and ()=>{} behave differently in terms of the scope and you have to use the former in this case.

3 Likes

Thanks a lot for your response!

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?

Thanks!

oh! it’s so close but that’s not how you initialize an array. I would suggest using

let c = [];

...

c.push(createCheckbox("check" + y));
c[x].changed(...)

Thanks again!

I’m doing this now, but the index is still wrong:

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 :slight_smile:

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!

1 Like

That makes sense :slight_smile:

Thanks a lot for your time!!!

1 Like