3

How to select and deselect all using lwc and I have multiple checkboxes on the page

<lightning-input data-id="toggle1" type="toggle"
                onchange={changeToggle}></lightning-input>
....
....
<lightning-input data-id="toggle10" type="toggle"
                onchange={selectall}></lightning-input>

JS

selectall(event) {
        let i; 
        let checkboxes = this.template.querySelectorAll('[data-id="toggle"]')
        for(i=0; i<checkboxes.length; i++) {
            checkboxes[i].checked = event.target.checked;
        }
    }

the above code works if all my checkboxes data-id="toggle" but I just want to keep the data-id unique is there a way I can say starting with toggle and ignore the numbers?

1 Answer 1

7

Since you want to get every lightning input which data-id starts with "toggle" your selector should be: [data-id^="toggle"]
You can find the whole list of CSS attribute selectors here.

Then if you want to check/uncheck them all via a single input your selectall method needs only a slightly change

selectall(event) {
    const toggleList = this.template.querySelectorAll('[data-id^="toggle"]');
    for (const toggleElement of toggleList) {
        toggleElement.checked = event.target.checked;
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .