I have an array of options stored in my database. I’m calling the info back and I want to populate a checkbox group with checkmarks based on that information. My current array contains all 4 options, so I am trying to show all 4 checkboxes as checked. However, I think the way I’m doing it is overriding itself each time and thus all I get is the LAST checkbox. I’m not sure how to write this so I can populate all 4 checkboxes.
Here’s what I’ve tried so far:
if(resultsc.items[0].goodWith[0] === "dogs"){
$w('#goodWith').selectedIndices = [0,0];
}
if(resultsc.items[0].goodWith[1] === "cats"){
$w('#goodWith').selectedIndices = [1,1];
}
if(resultsc.items[0].goodWith[2] === "kids"){
$w('#goodWith').selectedIndices = [2,2];
}
if(resultsc.items[0].goodWith[3] === "teens"){
$w('#goodWith').selectedIndices = [3,3];
}
I considered trying a for loop or something similar but I couldn’t see how to make it work.
Thanks for your help!
Hi there
Yes, what you’re doing is exactly as you suspected, you’re overwriting the value each time, the selectedIndices take the indexes of boxes you wish to mark, and you’re passing the very same index twice, each time.
To pull this off, we’re going to create an array of values, and their indexes, then run a for loop against the array from your database (the order won’t matter), if the values match, we’ll add the index to another array, then, when we’re done, we’ll assign the final array of indexes to the selected indices of the element. Let me demonstrate.
const indexes = []; // The array we'll assign to the element at the end.
const data = resultsc.items[0].goodWith; // The data array we want to inspect
// Our group of check boxes reference data
const ref = [
{ prop: 'dogs', i: 0 },
{ prop: 'cats', i: 1 },
{ prop: 'kids', i: 2 },
{ prop: 'teens', i: 3 },
]
// Create a for loop
for (const item of ref) {
data.includes(item.prop) ? indexes.push(item.i) : null;
}
// Assign the indexes array to the selected indices of the element
$w('#goodWith').selectedIndices = indexes;
And that’s it, hope this helps~!
Ahmad
Much appreciated! The only issue is it says continue is an error: “expression expected - parsing error, unexpected token”
Nevermind when I changed it to “false” it corrected itself! Thank you!!
@raraavismedia Yes, change it to either false or null and it will work.