Collapse Checkbox if Unchecked

Hi there!

Hoping someone can help :slight_smile:

I am trying to create a dynamic page linked to a database. This database has many boolean values that are linked to checkboxes on my page. I would like the checkboxes to collapse if their value is null. Is it possible to do by coding?

Thank you very much in advance!

Hi Ivana :raised_hand_with_fingers_splayed:

Yes it’s possible, only add the options that are true to the checkbox group items.

const item = {}; // And object retrieved from the dataset or database

const options = []; // The options we want to show
const reqOptions = ['opt1', 'opt2', 'opt3']; // The fields that you want to check

reqOptions.forEach(prop=> {
    // Check if the field value it truthy
    if (item[prop]) { options.push({ label: item[prop], value: item[prop] }) }
})

// Apply the options
$w('#checkboxGroup').options = options;

Hope this helps~!
Ahmad

Hi Ahmad,

Thank you for this!

Apologies if I am being silly, that only applies to checkboxgroup, not for “solo” checkboxes, right?

I have them as solo checkboxes (as it was the easiest way I found to link them to booleans in my database). And the logic would be if its own value (now that the element received its value from the database) is null, collapse.

Can you please help? :see_no_evil:

I have tried:

let isChecked = $w ( ‘#checkbox1’ ). checked ;
if ( isChecked === false ){
$w ( ‘#checkbox1’ ). collapse ()
}

But it only catches the value of the checkbox on my editor page, and not its value after being populated by my database (the page is a dynamic page).

Any help, please…?

@ivana by looking at the checkboxes I assumed they’re checkboxgroup, because that’s the way it should be implemented, anyway …

You’ll need to store the IDs of the checkboxes and their databse values like so

const elements = [
    {
        id: checkbox1, // The ID of the element
        field: 'isTrue' // The name of the field in the database
    },
    {
        id: checkbox2,
        field: 'isTrue'
    }
]

Then, once the dataset is ready, check the fields and collapse the fields if the value is falsy.

$w('#dataset').onReady(() => {
    const item = $w('#dataset').getCurrentItem();
    
    elements.forEach(element => {
        (!item[element.field]) { $w(`#${element.id}`).collapse() }
    })
})

That’s it.
Hope this helps~!