Skip to content
WebJs
Menu

A control that allows the user to toggle between checked and not checked.

By clicking this checkbox, you agree to the terms.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass,
  fieldTitleClass, fieldDescriptionClass,
} from '#components/ui/field.ts';
import { labelClass } from '#components/ui/label.ts';

export default function CheckboxDemo() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'max-w-sm')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox" name="terms-checkbox" class=${checkboxClass()}>
        <label data-slot="label" for="terms-checkbox" class=${labelClass()}>Accept terms and conditions</label>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-2" name="terms-checkbox-2" checked class=${checkboxClass()}>
        <div data-slot="field-content" class=${fieldContentClass()}>
          <label data-slot="field-label" for="terms-checkbox-2" class=${fieldLabelClass()}>
            Accept terms and conditions
          </label>
          <p data-slot="field-description" class=${fieldDescriptionClass()}>
            By clicking this checkbox, you agree to the terms.
          </p>
        </div>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="toggle-checkbox" name="toggle-checkbox" disabled class=${checkboxClass()}>
        <label data-slot="field-label" for="toggle-checkbox" class=${fieldLabelClass()}>Enable notifications</label>
      </div>
      <label data-slot="field-label" class=${fieldLabelClass()}>
        <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
          <input type="checkbox" data-slot="checkbox" id="toggle-checkbox-2" name="toggle-checkbox-2" class=${checkboxClass()}>
          <div data-slot="field-content" class=${fieldContentClass()}>
            <div data-slot="field-label" class=${fieldTitleClass()}>Enable notifications</div>
            <p data-slot="field-description" class=${fieldDescriptionClass()}>
              You can enable or disable notifications at any time.
            </p>
          </div>
        </div>
      </label>
    </div>
  `;
}
View Code

Installation

pnpm dlx @webjsdev/ui add checkbox

Usage

import { checkboxClass } from '#components/ui/checkbox.ts';
<input type="checkbox" data-slot="checkbox" class=${checkboxClass()}>

Checked State

The checkbox is a native <input type="checkbox">, so it keeps its own state. Use the checked attribute for the initial state, and read or set the checked property, listening for the change event, to follow it.

<input
  type="checkbox"
  data-slot="checkbox"
  checked
  class=${checkboxClass()}
  @change=${(e: Event) => this.onCheckedChange((e.target as HTMLInputElement).checked)}
>

Invalid State

Set aria-invalid on the checkbox and data-invalid on the field wrapper to show the invalid styles.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function CheckboxInvalid() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-56')}>
      <div role="group" data-slot="field" data-orientation="horizontal" data-invalid="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input
          type="checkbox"
          data-slot="checkbox"
          id="terms-checkbox-invalid"
          name="terms-checkbox-invalid"
          aria-invalid="true"
          class=${checkboxClass()}
        >
        <label data-slot="field-label" for="terms-checkbox-invalid" class=${fieldLabelClass()}>
          Accept terms and conditions
        </label>
      </div>
    </div>
  `;
}
View Code

Basic

Pair the checkbox with fieldClass() and fieldLabelClass() for proper layout and labeling.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function CheckboxBasic() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-56')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-basic" name="terms-checkbox-basic" class=${checkboxClass()}>
        <label data-slot="field-label" for="terms-checkbox-basic" class=${fieldLabelClass()}>
          Accept terms and conditions
        </label>
      </div>
    </div>
  `;
}
View Code

Description

Use fieldContentClass() and fieldDescriptionClass() for helper text.

By clicking this checkbox, you agree to the terms and conditions.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass, fieldDescriptionClass,
} from '#components/ui/field.ts';

export default function CheckboxDescription() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-72')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input
          type="checkbox"
          data-slot="checkbox"
          id="terms-checkbox-desc"
          name="terms-checkbox-desc"
          checked
          class=${checkboxClass()}
        >
        <div data-slot="field-content" class=${fieldContentClass()}>
          <label data-slot="field-label" for="terms-checkbox-desc" class=${fieldLabelClass()}>
            Accept terms and conditions
          </label>
          <p data-slot="field-description" class=${fieldDescriptionClass()}>
            By clicking this checkbox, you agree to the terms and conditions.
          </p>
        </div>
      </div>
    </div>
  `;
}
View Code

Disabled

Use the disabled attribute to prevent interaction and add the data-disabled attribute to the field for disabled styles.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function CheckboxDisabled() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-56')}>
      <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input
          type="checkbox"
          data-slot="checkbox"
          id="toggle-checkbox-disabled"
          name="toggle-checkbox-disabled"
          disabled
          class=${checkboxClass()}
        >
        <label data-slot="field-label" for="toggle-checkbox-disabled" class=${fieldLabelClass()}>
          Enable notifications
        </label>
      </div>
    </div>
  `;
}
View Code

Group

Use multiple fields to create a checkbox list.

Show these items on the desktop:

Select the items you want to show on the desktop.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldSetClass, fieldLegendClass, fieldDescriptionClass, fieldGroupClass, fieldClass, fieldLabelClass,
} from '#components/ui/field.ts';

const items = [
  { id: 'finder-pref-9k2-hard-disks-ljj-checkbox', label: 'Hard disks', checked: true },
  { id: 'finder-pref-9k2-external-disks-1yg-checkbox', label: 'External disks', checked: true },
  { id: 'finder-pref-9k2-cds-dvds-fzt-checkbox', label: 'CDs, DVDs, and iPods', checked: false },
  { id: 'finder-pref-9k2-connected-servers-6l2-checkbox', label: 'Connected servers', checked: false },
];

export default function CheckboxGroup() {
  return html`
    <fieldset data-slot="field-set" class=${fieldSetClass()}>
      <legend data-slot="field-legend" data-variant="label" class=${fieldLegendClass({ variant: 'label' })}>
        Show these items on the desktop:
      </legend>
      <p data-slot="field-description" class=${fieldDescriptionClass()}>
        Select the items you want to show on the desktop.
      </p>
      <div data-slot="field-group" class=${cn(fieldGroupClass(), 'gap-3')}>
        ${items.map((item) => html`
          <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
            <input type="checkbox" data-slot="checkbox" id=${item.id} name=${item.id} ?checked=${item.checked} class=${checkboxClass()}>
            <label data-slot="field-label" for=${item.id} class=${cn(fieldLabelClass(), 'font-normal')}>${item.label}</label>
          </div>
        `)}
      </div>
    </fieldset>
  `;
}
View Code

Table

Name Email Role
Sarah Chen [email protected] Admin
Marcus Rodriguez [email protected] User
Priya Patel [email protected] User
David Kim [email protected] Editor
import { html, nothing } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  tableContainerClass, tableClass, tableHeaderClass, tableBodyClass,
  tableRowClass, tableHeadClass, tableCellClass,
} from '#components/ui/table.ts';

const tableData = [
  { id: '1', name: 'Sarah Chen', email: '[email protected]', role: 'Admin' },
  { id: '2', name: 'Marcus Rodriguez', email: '[email protected]', role: 'User' },
  { id: '3', name: 'Priya Patel', email: '[email protected]', role: 'User' },
  { id: '4', name: 'David Kim', email: '[email protected]', role: 'Editor' },
];

// The first row starts selected. data-state="selected" is what the row's
// selected style keys on, so it travels with the checked box.
const selected = new Set(['1']);

export default function CheckboxTable() {
  return html`
    <div data-slot="table-container" class=${tableContainerClass()}>
      <table data-slot="table" class=${tableClass()}>
        <thead data-slot="table-header" class=${tableHeaderClass()}>
          <tr data-slot="table-row" class=${tableRowClass()}>
            <th scope="col" data-slot="table-head" class=${cn(tableHeadClass(), 'w-8')}>
              <input
                type="checkbox"
                data-slot="checkbox"
                id="select-all-checkbox"
                name="select-all-checkbox"
                aria-label="Select all"
                ?checked=${selected.size === tableData.length}
                class=${checkboxClass()}
              >
            </th>
            <th scope="col" data-slot="table-head" class=${tableHeadClass()}>Name</th>
            <th scope="col" data-slot="table-head" class=${tableHeadClass()}>Email</th>
            <th scope="col" data-slot="table-head" class=${tableHeadClass()}>Role</th>
          </tr>
        </thead>
        <tbody data-slot="table-body" class=${tableBodyClass()}>
          ${tableData.map((row) => html`
            <tr data-slot="table-row" data-state=${selected.has(row.id) ? 'selected' : nothing} class=${tableRowClass()}>
              <td data-slot="table-cell" class=${tableCellClass()}>
                <input
                  type="checkbox"
                  data-slot="checkbox"
                  id=${`row-${row.id}-checkbox`}
                  name=${`row-${row.id}-checkbox`}
                  aria-label=${`Select ${row.name}`}
                  ?checked=${selected.has(row.id)}
                  class=${checkboxClass()}
                >
              </td>
              <td data-slot="table-cell" class=${cn(tableCellClass(), 'font-medium')}>${row.name}</td>
              <td data-slot="table-cell" class=${tableCellClass()}>${row.email}</td>
              <td data-slot="table-cell" class=${tableCellClass()}>${row.role}</td>
            </tr>
          `)}
        </tbody>
      </table>
    </div>
  `;
}
View Code

RTL

To enable RTL support, see the RTL configuration guide.

بالنقر على هذا المربع، فإنك توافق على الشروط.

import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass,
  fieldTitleClass, fieldDescriptionClass,
} from '#components/ui/field.ts';
import { labelClass } from '#components/ui/label.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      acceptTerms: 'Accept terms and conditions',
      acceptTermsDescription: 'By clicking this checkbox, you agree to the terms.',
      enableNotifications: 'Enable notifications',
      enableNotificationsDescription: 'You can enable or disable notifications at any time.',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      acceptTerms: 'قبول الشروط والأحكام',
      acceptTermsDescription: 'بالنقر على هذا المربع، فإنك توافق على الشروط.',
      enableNotifications: 'تفعيل الإشعارات',
      enableNotificationsDescription: 'يمكنك تفعيل أو إلغاء تفعيل الإشعارات في أي وقت.',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      acceptTerms: 'קבל תנאים והגבלות',
      acceptTermsDescription: 'על ידי לחיצה על תיבת הסימון הזו, אתה מסכים לתנאים.',
      enableNotifications: 'הפעל התראות',
      enableNotificationsDescription: 'אתה יכול להפעיל או להשבית התראות בכל עת.',
    },
  },
};

// The provider is the dir attribute: every part styles itself with logical
// properties, so dir="rtl" on the group flips the whole layout.
export default function CheckboxRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <div data-slot="field-group" dir=${dir} lang=${lang} class=${cn(fieldGroupClass(), 'max-w-sm')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-rtl" name="terms-checkbox" class=${checkboxClass()}>
        <label data-slot="label" for="terms-checkbox-rtl" class=${labelClass()}>${t.acceptTerms}</label>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-2-rtl" name="terms-checkbox-2" checked class=${checkboxClass()}>
        <div data-slot="field-content" class=${fieldContentClass()}>
          <label data-slot="field-label" for="terms-checkbox-2-rtl" class=${fieldLabelClass()}>${t.acceptTerms}</label>
          <p data-slot="field-description" class=${fieldDescriptionClass()}>${t.acceptTermsDescription}</p>
        </div>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="toggle-checkbox-rtl" name="toggle-checkbox" disabled class=${checkboxClass()}>
        <label data-slot="field-label" for="toggle-checkbox-rtl" class=${fieldLabelClass()}>${t.enableNotifications}</label>
      </div>
      <label data-slot="field-label" class=${fieldLabelClass()}>
        <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
          <input type="checkbox" data-slot="checkbox" id="toggle-checkbox-2-rtl" name="toggle-checkbox-2" class=${checkboxClass()}>
          <div data-slot="field-content" class=${fieldContentClass()}>
            <div data-slot="field-label" class=${fieldTitleClass()}>${t.enableNotifications}</div>
            <p data-slot="field-description" class=${fieldDescriptionClass()}>${t.enableNotificationsDescription}</p>
          </div>
        </div>
      </label>
    </div>
  `;
}
View Code

API Reference

checkboxClass

checkboxClass() returns the classes for a native <input type="checkbox"> and takes no options. The checkbox is a real form control, so it submits with its <form> and supports every native attribute.

AttributeTypeDefault
data-slot"checkbox"required
checkedbooleanfalse
disabledbooleanfalse
requiredbooleanfalse
namestring-
valuestring"on"
aria-invalid"true"-

data-slot="checkbox" is required: the checkmark is drawn by a stylesheet keyed on it. The indeterminate state is the indeterminate property (el.indeterminate = true), not an attribute.