11

To make a checkbox in LWC checked by default it has to have the "checked" attribute inside the markup and it is not responding on placing value=true or value= false inside the markup. But is there any way to assign a variable that would store the value.

lightning-input  class="slds-p-left_xx-large" type="checkbox" label="" onchange={handleChange} checked

I also tried to make the "checked" attribute a dynamic string variable but that too didn't work.

Basically I want to Select all checkbox clicking on which it will select the other checkboxes. But I am unable to assign any dynamic value to check and uncheck the boxes. Is there any workaround to it for LWC?

2 Answers 2

19

You can add attribute checked to lightning-input from javascript controller. You can access checkbox element by some attribute. In this example all checkboxes are accessed by setting data-id attribute.

html file -

<template>
    <lightning-input class="slds-p-left_xx-large" type="checkbox" label="checkbox Select All" onchange={handleChange} ></lightning-input>

    <lightning-input class="slds-p-left_xx-large" type="checkbox" data-id="checkbox" label="checkbox" ></lightning-input>
    <lightning-input class="slds-p-left_xx-large" type="checkbox" data-id="checkbox" label="checkbox" ></lightning-input>
    <lightning-input class="slds-p-left_xx-large" type="checkbox" data-id="checkbox" label="checkbox" ></lightning-input>
</template>

js controller-

import { LightningElement, track, api } from 'lwc';

export default class lwcCmpName extends LightningElement {
    handleChange(event) {
        let i;
        let checkboxes = this.template.querySelectorAll('[data-id="checkbox"]')
        for(i=0; i<checkboxes.length; i++) {
            checkboxes[i].checked = event.target.checked;
        }
    }
}

Here when Checkbox Select All will be checked all other checkboxes will be checked and same for unchecked.

2
  • Hey Amit, Thanks a lot.It worked perfectly as required. Commented Dec 13, 2019 at 8:11
  • Welcome @PriyankurChoudhury. You can accept this answer so that it will be helpful to others. Commented Dec 13, 2019 at 8:16
12

You can check it directly like this.

<lightning-input label="test" class="slds-p-left_xx-large" type="checkbox" checked="checked">
</lightning-input>

OR

You can check the box from the JS controller dynamically like this.

HTML

<template>
    <lightning-input label="test" class="slds-p-left_xx-large" type="checkbox" checked={checkboxVal} >
    </lightning-input>
</template>

JS

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    checkboxVal = true;
}

You must log in to answer this question.

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