---
schema_version: "1"
id: 6edcef518011d2a661c853f0ec05b6d3d7dc3b5f04b0781285ddedd6e07b9d7c
title: Checkbox
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/lightning-base-components/lightning-design-system/guides/lwc/components/lightning/checkbox/lightning-checkbox.md
canonical_url: https://developer.salesforce.com/docs/platform/lightning-component-reference/guide/lightning-checkbox.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: fc5de68fd09257e1c46679e2c3406fc94f21134fb50353c6d74b1c3f3843aafb
products:
  - Lightning Component Reference
---

# Checkbox

**`lightning-input`**
_type="checkbox"_

**For Use In**

Lightning Experience, Experience Builder Sites, Salesforce Mobile App, Lightning Out (Beta), Standalone Lightning App, Mobile Offline

::::::tabset{tabs='["Example", "Develop", "Specifications"]'}

:::::tab

::component-playground{component="checkbox" model="lwc" namespace="lightning"}


:::::

:::::tab

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`](/docs/platform/lightning-component-reference/guide/lightning-checkbox-group.html) instead.

<!-- prettier-ignore-start -->
```html
<template>
    <lightning-input type="checkbox" label="Red" checked> </lightning-input>
    <lightning-input type="checkbox"> </lightning-input>
</template>
```
<!-- prettier-ignore-end -->

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](https://help.salesforce.com/s/articleView?id=xcloud.customize_ui_enhancedlex.htm) based on the org's theme or the container app that you use.

| Input Type | SLDS 1                                                                | SLDS 2                                                                 |
| ---------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| checkbox   | [Checkbox](https://v1.lightningdesignsystem.com/components/checkbox/) | [Checkbox](https://www.lightningdesignsystem.com/components/checkbox/) |

## 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.

<!-- prettier-ignore -->
```html
<template>
    <lightning-input
        type="checkbox"
        label="Select All"
        checked={allSelected}
        indeterminate={someSelected}
        onchange={handleSelectAllChange}
    >
    </lightning-input>

    <!-- A group of checkboxes -->
    <div class="slds-var-m-top_small slds-var-p-left_large">
        <template for:each={checkboxItems} for:item="item">
            <lightning-input
                key={item.id}
                type="checkbox"
                label={item.label}
                checked={item.checked}
                data-id={item.id}
                onchange={handleItemChange}
            >
            </lightning-input>
        </template>
    </div>

    <p class="slds-var-m-top_small">
        Selected: {selectedCount} of {totalCount}
    </p>
</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.

```javascript
import { LightningElement } from "lwc";

export default class BaseComponents extends LightningElement {
  checkboxItems = [
    { id: "red", label: "Red", checked: false },
    { id: "green", label: "Green", checked: true },
    { id: "blue", label: "Blue", checked: false },
  ];

  get selectedCount() {
    return this.checkboxItems.filter((item) => item.checked).length;
  }

  get totalCount() {
    return this.checkboxItems.length;
  }

  get allSelected() {
    return this.totalCount > 0 && this.selectedCount === this.totalCount;
  }

  get someSelected() {
    return this.selectedCount > 0 && this.selectedCount < this.totalCount;
  }

  handleSelectAllChange(event) {
    const isChecked = event.target.checked;
    this.checkboxItems = this.checkboxItems.map((item) => ({
      ...item,
      checked: isChecked,
    }));
  }

  handleItemChange(event) {
    const selectedId = event.target.dataset.id;
    const isChecked = event.target.checked;
    this.checkboxItems = this.checkboxItems.map((item) =>
      item.id === selectedId ? { ...item, checked: isChecked } : item,
    );
  }
}
```

## 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.

<!-- prettier-ignore-start -->
```html
<template>
    <lightning-input
        type="checkbox"
        label="Red"
        onchange={handleCheckboxChange}
    >
    </lightning-input>
    <lightning-input
        type="checkbox"
        label="Blue"
        onchange={handleCheckboxChange}
    >
    </lightning-input>
    <lightning-input
        type="checkbox"
        label="Green"
        onchange={handleCheckboxChange}
    >
    </lightning-input>

    <p>Checked items: {selection}</p>
</template>
```
<!-- prettier-ignore-end -->

When you select a checkbox, the `handleCheckboxChange` function updates the `selection` property to display a list of selected checkboxes.

```javascript
import { LightningElement } from "lwc";

export default class CheckboxExample extends LightningElement {
  selection;

  handleCheckboxChange() {
    // Query the DOM
    const checked = Array.from(this.template.querySelectorAll("lightning-input"))
      // Filter down to checked items
      .filter((element) => element.checked)
      // Map checked items to their labels
      .map((element) => element.label);
    this.selection = checked.join(", ");
  }
}
```

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.

<!-- prettier-ignore-start -->
```html
<template>
    <lightning-input
        type="checkbox"
        data-element="subscribe-checkbox"
        label="Subscribe"
    >
    </lightning-input>
    <lightning-button
        label="Subscribe"
        onclick={handleSubscribe}
    ></lightning-button>
</template>
```
<!-- prettier-ignore-end -->

Set the element's `checked` property to `true`.

```javascript
import { LightningElement } from "lwc";

export default class CheckboxExample extends LightningElement {
  handleSubscribe(event) {
    this.template.querySelectorAll('[data-element="subscribe-checkbox"]').forEach((element) => {
      element.checked = true;
    });
  }
}
```

## 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.

<!-- prettier-ignore -->
```html
<template>
  <lightning-input
    type="checkbox"
    label="I agree to the terms and conditions"
    required
    lwc:ref="termsCheckbox"
    message-when-value-missing="Please accept the terms and conditions"
  >
  </lightning-input>
  <lightning-button label="Submit" onclick={handleSubmit}></lightning-button>
</template>
```

**note:** For the default error messages, see the [`lightning-input` documentation](/docs/platform/lightning-component-reference/guide/lightning-input.html).

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.

```javascript
import { LightningElement } from "lwc";

export default class CheckboxValidation extends LightningElement {
  handleSubmit() {
    const checkbox = this.refs.termsCheckbox;
    console.log(checkbox.validity.valid); // Returns true or false
    if (!checkbox.checkValidity()) {
      checkbox.reportValidity();
      return;
    }
    // Proceed with form submission
  }
}
```

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.

<!-- prettier-ignore-start -->
```html
<template>
    <lightning-input
        type="checkbox"
        label="Subscribe to newsletter"
        field-level-help="You will receive weekly updates about new features and promotions"
    >
    </lightning-input>
    <lightning-input
        type="checkbox"
        label="Enable notifications"
        field-level-help="Push notifications will be sent to your device when important events occur"
    >
    </lightning-input>
</template>
```
<!-- prettier-ignore-end -->

## 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](https://v1.lightningdesignsystem.com/utilities/alignment) 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](https://v1.lightningdesignsystem.com/components/overview/) for available component styling hooks.

For more information, see [Style Components Using Lightning Design System Styling Hooks](https://developer.salesforce.com/docs/platform/lwc/guide/create-components-css-custom-properties) 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](/docs/platform/lightning-component-reference/guide/lightning-input.html?type=Specifications).

## Custom Events

**`change`**

The event fired when a value is changed in the input field.

The `change` event returns this `event.target` parameter.

| Parameter | Type    | Description                                                                                                                          |
| --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| checked   | boolean | The value of the `checked` attribute. See [Handle Selections](#handle-selections) for an example of working with an array of inputs. |

The event properties are as follows.

| Property   | Value | Description                                                                                               |
| ---------- | ----- | --------------------------------------------------------------------------------------------------------- |
| bubbles    | true  | This event bubbles up through the DOM.                                                                    |
| cancelable | false | This event has no default behavior that can be canceled. You can't call `preventDefault()` on this event. |
| composed   | true  | This event propagates outside of the component in which it was dispatched.                                |

## See Also

[`lightning-input`](/docs/platform/lightning-component-reference/guide/lightning-input.html)


:::::

:::::tab
For this component's attributes and methods, see the [`lightning-input` Specifications tab](/docs/platform/lightning-component-reference/guide/lightning-input.html?type=Specifications).


:::::

::::::
