More efficient way to do this? (photo)

Hi, I want to do this for 29 checkboxes :

I CAN do it with this:


export function checkbox1_change(event) {
 if ($w("#checkbox1").checked) {
        $w("#textDescription").text = "This is text sent here after checking #checkbox1";
    } 
 else
        $w("#textDescription").text = "";
}

But is there a more efficient/clever way?

    $w("#cb0,#cb1,#cb2,#cb3,#cb...").onChange( (event) => { 
        console.log(event.target.id);
        //...
    });

Additional to yvervoort suggestion, another possibility (should be improved a little bit to get a perfect result).

$w('Checkbox').onChange((event)=>{
 let selectedElement = event.target.id
 
  for (var i = 0; i < PutInHereTheLengthOfCheckboxes; i++) {
     switch(selectedElement)){
       case ("checkbox"+i): 
          $w("#textDescription").text = "This is text sent here after checking
       break;
     }
   }
})

Select by class or id (multi ids)
Class $w( ‘Checkbox’ ).onClick…
Id $w(‘#checkbox1, #checkbox2, …’).onClick…

@mvveiga @vervoortyves @russian-dima

Thank you all very much for your time replying to my post. All these approaches are very effective and clever. I don’t know though, how would you deal with the fact that each and every checkbox is related to a different .text… So cb1, when checked, displays text1, cb2–>text2, … cb29–>text29.

@gemats
Use an —> ARRAY —> for your textes

myArray = []
myArray.push()

// make it so, that you have this at the end.....
myArray = ["text1", "text2", "text3"] //---< and so on.....


console.log(myArray[0])
console.log(myArray[1])
console.log(myArray[2])

// + ---> loop

In my example, i already gave you the idea with the loop.

Now try to combine both of my ideas :wink:

You wanna improve it?
No problem!

let myText1 = "Here is my first text, whatever it is, i don't know"
let myText2 ="Here will be my second one"
let myText3 = "And here we will have the third text-example"

myArray = [myText1, myText2, myText3]

You wanna improve it???

No problem —> connect this part with your DATABASE, and load all your textes from your DATABASE!

Good luck and happy coding.:wink:

You wanna improve it more?

Ok, i think it should be enough improvement for the first time :grin:

@gemats depending on how far you want to go with this, I’d suggest to work with an intermediate object which contains the data to populate your UI components.

You can either choose to manually add the data to the object in your application layer, but getting it from the database is also an option.

var nbItems = 29; //get from db
var cb = {
 "label": "",
 "description": ""
}

var obj = [];
for(i=0;i<nbItems;i++){
 cb.label = db[i].label;
 cb.description = db[i].description;
 obj.push(cb);
}
console.log(obj);

//populate UI elements