Skip to content

Checkbox group ​

Related checkboxes in a fieldset, with a "Select all" box, a minimum selection and an error message.

Installation ​

bash
npx bootcn add checkbox-group
bash
pnpm dlx bootcn add checkbox-group
bash
yarn dlx bootcn add checkbox-group
bash
bunx --bun bootcn add checkbox-group

The CLI also installs the design tokens and these components: checkbox. It prints the <link> and <script> tags to add to your layout.

Usage ​

Give the items one name ending in [], so PHP receives an array ($_POST['notify']). Add bootcn-checkbox-group--horizontal for short labels in a row.

JavaScript API ​

  • data-bootcn-checkbox-group on the <fieldset>. Optional: a "Select all" checkbox with data-bootcn-checkbox-group-all (checked, unchecked or mixed as the items change), data-min (fewest checked boxes) with data-error (the message), and an element .bootcn-checkbox-group__error for it.
  • Below the minimum, the first checkbox gets a custom validity message, so form.checkValidity() fails too. Submitting the form shows the error, stops the submission and focuses the first checkbox.
  • Event bootcn:checkbox-group:change (bubbles), detail.values.
  • Bootcn.checkboxGroup.validate(group); init() / destroy().
  • Without JavaScript the boxes still post as name[] values; check the minimum on the server too.

Accessibility ​

  • A <fieldset> with a <legend> names the group; the help text and the error are linked with aria-describedby.
  • "Select all" controls the items (aria-controls) and shows the mixed state with indeterminate, which screen readers announce as "mixed".
  • The error is text, not only a red border.

Dependencies ​

  • Bootstrap 5.3+ CSS.
  • themes/tokens/tokens.css.
  • The checkbox component.

Source ​

The exact files the CLI installs (checkbox-group@1.0.0). View on GitHub · Report an issue

html
<form class="bootcn-checkbox-group-demo" action="#">
  <fieldset
    class="bootcn-checkbox-group"
    data-bootcn-checkbox-group
    data-min="1"
    data-error="Choose at least one channel."
    aria-describedby="bootcn-checkbox-group-help"
  >
    <legend class="bootcn-checkbox-group__legend">Notifications</legend>
    <p class="bootcn-checkbox-group__help" id="bootcn-checkbox-group-help">
      Where should we send updates about your orders?
    </p>
    <div class="form-check bootcn-checkbox">
      <input
        class="form-check-input bootcn-checkbox__input"
        type="checkbox"
        id="bootcn-checkbox-group-all"
        data-bootcn-checkbox-group-all
        aria-controls="bootcn-checkbox-group-email bootcn-checkbox-group-sms bootcn-checkbox-group-push bootcn-checkbox-group-slack"
      />
      <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-all"
        >Select all</label
      >
    </div>
    <div class="bootcn-checkbox-group__items">
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-email"
          name="notify[]"
          value="email"
          checked
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-email"
          >Email</label
        >
      </div>
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-sms"
          name="notify[]"
          value="sms"
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-sms"
          >Text message</label
        >
      </div>
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-push"
          name="notify[]"
          value="push"
          checked
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-push"
          >Push notification</label
        >
      </div>
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-slack"
          name="notify[]"
          value="slack"
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-slack"
          >Slack</label
        >
      </div>
    </div>
    <p class="bootcn-checkbox-group__error" id="bootcn-checkbox-group-error" hidden></p>
  </fieldset>

  <fieldset class="bootcn-checkbox-group bootcn-checkbox-group--horizontal mt-4">
    <legend class="bootcn-checkbox-group__legend">Sizes</legend>
    <div class="bootcn-checkbox-group__items">
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-size-s"
          name="size[]"
          value="s"
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-size-s"
          >S</label
        >
      </div>
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-size-m"
          name="size[]"
          value="m"
          checked
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-size-m"
          >M</label
        >
      </div>
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-size-l"
          name="size[]"
          value="l"
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-size-l"
          >L</label
        >
      </div>
      <div class="form-check bootcn-checkbox">
        <input
          class="form-check-input bootcn-checkbox__input"
          type="checkbox"
          id="bootcn-checkbox-group-size-xl"
          name="size[]"
          value="xl"
        />
        <label class="form-check-label bootcn-checkbox__label" for="bootcn-checkbox-group-size-xl"
          >XL</label
        >
      </div>
    </div>
  </fieldset>

  <button type="submit" class="btn bootcn-button bootcn-button--default mt-4">Save</button>
</form>
css
.bootcn-checkbox-group {
  min-width: 0;
  margin: 0;
  padding: 0;
  border: 0;
}

.bootcn-checkbox-group__legend {
  float: none;
  width: auto;
  margin: 0 0 0.25rem;
  padding: 0;
  font-size: 0.875rem;
  font-weight: 500;
}

.bootcn-checkbox-group__help {
  margin: 0 0 0.75rem;
  color: var(--bootcn-muted-foreground);
  font-size: 0.875rem;
}

.bootcn-checkbox-group__items {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

/* "Select all" sits above the items, separated by a rule. */
.bootcn-checkbox-group > .bootcn-checkbox {
  margin-bottom: 0.75rem;
  padding-bottom: 0.75rem;
  border-bottom: var(--bootcn-border-width) solid var(--bootcn-border-color);
}

.bootcn-checkbox-group__items .bootcn-checkbox {
  margin: 0;
}

.bootcn-checkbox-group--horizontal .bootcn-checkbox-group__items {
  flex-flow: row wrap;
  gap: 0.75rem 1.5rem;
}

.bootcn-checkbox-group__error {
  margin: 0.75rem 0 0;
  color: var(--bootcn-destructive-text);
  font-size: 0.875rem;
}

.bootcn-checkbox-group.is-invalid .bootcn-checkbox__input {
  border-color: var(--bs-danger);
}

/* Preview layout only. */
.bootcn-checkbox-group-demo {
  width: 20rem;
  max-width: 100%;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.checkboxGroup) return; // already loaded: idempotent

  const ROOT = '[data-bootcn-checkbox-group]';
  const ALL = '[data-bootcn-checkbox-group-all]';
  let listening = false;

  function boxes(group) {
    return Array.from(
      group.querySelectorAll('.bootcn-checkbox-group__items input[type="checkbox"]'),
    ).filter(function (box) {
      return !box.disabled;
    });
  }

  function syncAll(group) {
    const all = group.querySelector(ALL);
    if (!all) return;
    const list = boxes(group);
    const checked = list.filter(function (box) {
      return box.checked;
    }).length;
    all.checked = checked > 0 && checked === list.length;
    all.indeterminate = checked > 0 && checked < list.length;
  }

  // Returns true when the group meets data-min. The message goes on the first
  // checkbox with setCustomValidity, so form.checkValidity() sees it too.
  function validate(group, show) {
    const min = Number(group.getAttribute('data-min') || 0);
    const list = boxes(group);
    const count = list.filter(function (box) {
      return box.checked;
    }).length;
    const valid = count >= min;
    const message = group.getAttribute('data-error') || 'Choose at least ' + min + '.';
    if (list[0]) list[0].setCustomValidity(valid ? '' : message);
    const error = group.querySelector('.bootcn-checkbox-group__error');
    if (show || valid) {
      group.classList.toggle('is-invalid', !valid);
      if (error) {
        error.hidden = valid;
        error.textContent = valid ? '' : message;
        const described = (group.getAttribute('aria-describedby') || '')
          .split(/\s+/)
          .filter(function (id) {
            return id && id !== error.id;
          });
        if (!valid) described.push(error.id);
        if (described.length) group.setAttribute('aria-describedby', described.join(' '));
        else group.removeAttribute('aria-describedby');
      }
    }
    return valid;
  }

  function onChange(event) {
    const box = event.target;
    if (!box.matches || !box.matches('input[type="checkbox"]')) return;
    const group = box.closest(ROOT);
    if (!group) return;
    if (box.matches(ALL)) {
      boxes(group).forEach(function (other) {
        other.checked = box.checked;
      });
    }
    syncAll(group);
    validate(
      group,
      group.classList.contains('is-invalid') || group.dataset.bootcnTouched === 'true',
    );
    group.dataset.bootcnTouched = 'true';
    group.dispatchEvent(
      new CustomEvent('bootcn:checkbox-group:change', {
        bubbles: true,
        detail: {
          values: boxes(group)
            .filter(function (other) {
              return other.checked;
            })
            .map(function (other) {
              return other.value;
            }),
        },
      }),
    );
  }

  function onSubmit(event) {
    const form = event.target;
    if (!form.querySelectorAll) return;
    let first = null;
    form.querySelectorAll(ROOT).forEach(function (group) {
      if (!validate(group, true) && !first) first = boxes(group)[0] || null;
    });
    if (first) {
      event.preventDefault();
      event.stopImmediatePropagation();
      first.focus();
    }
  }

  function setup(group) {
    syncAll(group);
    validate(group, false);
  }

  function init() {
    if (!listening) {
      document.addEventListener('change', onChange);
      document.addEventListener('submit', onSubmit, true); // before other submit handlers
      listening = true;
    }
    document.querySelectorAll(ROOT).forEach(setup);
  }

  function destroy() {
    if (!listening) return;
    document.removeEventListener('change', onChange);
    document.removeEventListener('submit', onSubmit, true);
    listening = false;
  }

  ns.checkboxGroup = {
    init: init,
    destroy: destroy,
    validate: function (group) {
      return validate(group, true);
    },
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.