Checkbox

lightning-input type=“checkbox”

For Use In

Lightning Experience, Experience Builder Sites, Salesforce Mobile App, Lightning Out (Beta), Standalone Lightning App, Mobile Offline

Checkboxes present one or more options for selection. lightning-input type="checkbox" is useful for creating single checkboxes. If you are working with a group of checkboxes, consider using lightning-checkbox-group instead.

1<template>
2    <lightning-input type="checkbox" label="Red" checked> </lightning-input>
3    <lightning-input type="checkbox"> </lightning-input>
4</template>

A checkbox that’s disabled is grayed out and you can’t interact with it. A disabled checkbox isn’t focusable and isn’t submitted with the form. Similarly, you can’t interact with a read-only checkbox.

Design 

lightning-input implements designs in the Salesforce Lightning Design System (SLDS). The input types adapt to SLDS 1 or SLDS 2 styling based on the org’s theme or the container app that you use.

Input TypeSLDS 1SLDS 2
checkboxCheckboxCheckbox

Read-Only Checkbox 

Unlike the native <input type="checkbox"> element, a read-only checkbox that you create using lightning-input with type="checkbox" and read-only attributes isn’t focusable. You can’t interact with a read-only checkbox and it isn’t submitted with the form.

A read-only checkbox has these characteristics.

  • Displays a checkmark icon without an enclosing border when the checked attribute is used.
  • Displays a dotted square icon when the checked attribute isn’t used.

If the checkbox also has read-only specified, adding the required attribute to a checkbox has no effect.

Indeterminate Checkbox 

An indeterminate checkbox shows a dash indicator instead of a checkbox. Use an indeterminate checkbox when you want to show a “Select All” checkbox for a group of checkbox. The indeterminate checkbox shows a dash indicator when only some items in a group are selected. Clicking the checkbox clears the indeterminate state. An indeterminate checkbox with a dash indicator has a checked value of false.

This example shows a “Select All” checkbox and a group of checkboxes. The “select all” checkbox either selects or deselects all the checkboxes in the group. When all the checkboxes are selected and you deselect one of the checkboxes in the group, the “Select All” checkbox becomes an indeterminate checkbox that shows a dash indicator.

1<template>
2    <lightning-input
3        type="checkbox"
4        label="Select All"
5        checked={allSelected}
6        indeterminate={someSelected}
7        onchange={handleSelectAllChange}
8    >
9    </lightning-input>
10
11    <!-- A group of checkboxes -->
12    <div class="slds-var-m-top_small slds-var-p-left_large">
13        <template for:each={checkboxItems} for:item="item">
14            <lightning-input
15                key={item.id}
16                type="checkbox"
17                label={item.label}
18                checked={item.checked}
19                data-id={item.id}
20                onchange={handleItemChange}
21            >
22            </lightning-input>
23        </template>
24    </div>
25
26    <p class="slds-var-m-top_small">
27        Selected: {selectedCount} of {totalCount}
28    </p>
29</template>

The checkbox specifies true for the indeterminate boolean when the selected number of checkboxes is at least 1 but fewer than the total number of checkboxes in the group. In this scenario, only some checkboxes in the group are selected.

1import { LightningElement } from "lwc";
2
3export default class BaseComponents extends LightningElement {
4  checkboxItems = [
5    { id: "red", label: "Red", checked: false },
6    { id: "green", label: "Green", checked: true },
7    { id: "blue", label: "Blue", checked: false },
8  ];
9
10  get selectedCount() {
11    return this.checkboxItems.filter((item) => item.checked).length;
12  }
13
14  get totalCount() {
15    return this.checkboxItems.length;
16  }
17
18  get allSelected() {
19    return this.totalCount > 0 && this.selectedCount === this.totalCount;
20  }
21
22  get someSelected() {
23    return this.selectedCount > 0 && this.selectedCount < this.totalCount;
24  }
25
26  handleSelectAllChange(event) {
27    const isChecked = event.target.checked;
28    this.checkboxItems = this.checkboxItems.map((item) => ({
29      ...item,
30      checked: isChecked,
31    }));
32  }
33
34  handleItemChange(event) {
35    const selectedId = event.target.dataset.id;
36    const isChecked = event.target.checked;
37    this.checkboxItems = this.checkboxItems.map((item) =>
38      item.id === selectedId ? { ...item, checked: isChecked } : item,
39    );
40  }
41}

Handle Selections 

When working with checkboxes and toggle switches, use this.template.querySelectorAll to retrieve the array of components. You can use .filter to determine which elements are checked or unchecked. The next example displays the values of the selected checkboxes.

1<template>
2    <lightning-input
3        type="checkbox"
4        label="Red"
5        onchange={handleCheckboxChange}
6    >
7    </lightning-input>
8    <lightning-input
9        type="checkbox"
10        label="Blue"
11        onchange={handleCheckboxChange}
12    >
13    </lightning-input>
14    <lightning-input
15        type="checkbox"
16        label="Green"
17        onchange={handleCheckboxChange}
18    >
19    </lightning-input>
20
21    <p>Checked items: {selection}</p>
22</template>

When you select a checkbox, the handleCheckboxChange function updates the selection property to display a list of selected checkboxes.

1import { LightningElement } from "lwc";
2
3export default class CheckboxExample extends LightningElement {
4  selection;
5
6  handleCheckboxChange() {
7    // Query the DOM
8    const checked = Array.from(this.template.querySelectorAll("lightning-input"))
9      // Filter down to checked items
10      .filter((element) => element.checked)
11      // Map checked items to their labels
12      .map((element) => element.label);
13    this.selection = checked.join(", ");
14  }
15}

To programmatically set a checkbox or checkbox button to checked, query the element using a custom data attribute. You can’t query the internal elements of a Lightning web component. This example uses a custom attribute data-element to query the element. The checkbox is selected by clicking a button.

1<template>
2    <lightning-input
3        type="checkbox"
4        data-element="subscribe-checkbox"
5        label="Subscribe"
6    >
7    </lightning-input>
8    <lightning-button
9        label="Subscribe"
10        onclick={handleSubscribe}
11    ></lightning-button>
12</template>

Set the element’s checked property to true.

1import { LightningElement } from "lwc";
2
3export default class CheckboxExample extends LightningElement {
4  handleSubscribe(event) {
5    this.template.querySelectorAll('[data-element="subscribe-checkbox"]').forEach((element) => {
6      element.checked = true;
7    });
8  }
9}

Input Validation 

To ensure the checkbox is selected before form submission, use the required attribute. You can programmatically check the checkbox’s checked property in your validation logic.

1<template>
2  <lightning-input
3    type="checkbox"
4    label="I agree to the terms and conditions"
5    required
6    lwc:ref="termsCheckbox"
7    message-when-value-missing="Please accept the terms and conditions"
8  >
9  </lightning-input>
10  <lightning-button label="Submit" onclick={handleSubmit}></lightning-button>
11</template>

For the default error messages, see the lightning-input documentation.

Note

To validate the checkbox, check its validity using the checkValidity() method or access the checked property. If the value isn’t valid, the reportValidity() method shows the error message below the checkbox.

1import { LightningElement } from "lwc";
2
3export default class CheckboxValidation extends LightningElement {
4  handleSubmit() {
5    const checkbox = this.refs.termsCheckbox;
6    console.log(checkbox.validity.valid); // Returns true or false
7    if (!checkbox.checkValidity()) {
8      checkbox.reportValidity();
9      return;
10    }
11    // Proceed with form submission
12  }
13}

The validity attribute returns an object with read-only boolean properties. For the checkbox type, these attributes apply:

  • badInput - Indicates that the value is invalid for any input type
  • customError - Indicates that a custom error has been set using setCustomValidity()
  • valueMissing - Indicates that an empty value is provided when the required attribute is set for any input type
  • valid - True if none of the preceding properties are true

Add Field-Level Help 

To provide contextual help content, specify help text with the field-level-help attribute. Field-level help adds an info icon next to the input label, with a tooltip displaying the specified help text.

1<template>
2    <lightning-input
3        type="checkbox"
4        label="Subscribe to newsletter"
5        field-level-help="You will receive weekly updates about new features and promotions"
6    >
7    </lightning-input>
8    <lightning-input
9        type="checkbox"
10        label="Enable notifications"
11        field-level-help="Push notifications will be sent to your device when important events occur"
12    >
13    </lightning-input>
14</template>

Component Styling 

Use a combination of variants and utility classes to customize your checkboxes.

Variants 

Use the variant attribute with one of these values to position the labels differently relative to the checkbox.

  • standard is the default, which displays the label above the checkbox.
  • label-hidden hides the label but make it available to assistive technology. If you provide a value for field-level-help, the tooltip icon is still displayed.
  • label-inline aligns the label and field horizontally.
  • label-stacked places the label above the field.

In most contexts, a stacked label (standard or label-stacked variant) results in better readability and clarity. Use horizontal labels (label-inline variant) when you want to conserve vertical space and have fewer than 10 fields.

Utility Classes 

To apply additional styling, use the SLDS utility classes with the class attribute.

Styling Hooks 

Component styling hooks provide CSS custom properties that use the --slds-c-* prefix and they change styling for specific elements or properties of a component. Component styling hooks are supported for SLDS 1 only. See the SLDS 1 component blueprints for available component styling hooks.

For more information, see Style Components Using Lightning Design System Styling Hooks in the Lightning Web Components Developer Guide.

Accessibility 

When you use the label attribute, the component generates a unique ID for the internal <label> and uses a standard for attribute to link it to the checkbox.

If you use the label-hidden variant, the component maintains the for attribute to link between the checkbox and the label.

If you use the field-level-help attribute, the component creates an aria-describedby link between the checkbox and the help tooltip.

If the checkbox fails validation, the component adds aria-invalid="true" and links the error message to the input by using aria-describedby.

For additional ARIA attributes that you can use, see the lightning-input Specifications tab.

Custom Events 

change

The event fired when a value is changed in the input field.

The change event returns this event.target parameter.

ParameterTypeDescription
checkedbooleanThe value of the checked attribute. See Handle Selections for an example of working with an array of inputs.

The event properties are as follows.

PropertyValueDescription
bubblestrueThis event bubbles up through the DOM.
cancelablefalseThis event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composedtrueThis event propagates outside of the component in which it was dispatched.

See Also 

lightning-input

For this component’s attributes and methods, see the lightning-input Specifications tab.