Checkbox group
<gui-checkbox-group> is a group of checkboxes to pick any number of options out of a few. It
renders native checkboxes inside an element with the group role, named by the label. Its value
is the list of the checked options’ values.
import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const toppings = ['Cheese', 'Ham', 'Olives', 'Mushrooms'];
export function CheckboxGroupBasic() { return <GuiCheckboxGroup label="Toppings" options={toppings} />;}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/checkbox-group';
@Component({ selector: 'app-checkbox-group-basic', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-checkbox-group label="Toppings" [options]="toppings" ></gui-checkbox-group> `,})export class CheckboxGroupBasicComponent { toppings = ['Cheese', 'Ham', 'Olives', 'Mushrooms'];}<script setup lang="ts">import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const toppings = ['Cheese', 'Ham', 'Olives', 'Mushrooms'];</script>
<template> <gui-checkbox-group label="Toppings" :options.prop="toppings" ></gui-checkbox-group></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const toppings = ['Cheese', 'Ham', 'Olives', 'Mushrooms'];
@customElement('checkbox-group-basic')export class CheckboxGroupBasic extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <gui-checkbox-group label="Toppings" .options=${toppings} ></gui-checkbox-group> `; }}<gui-checkbox-group label="Toppings" options='["Cheese", "Ham", "Olives", "Mushrooms"]'></gui-checkbox-group>The element’s entry point is @golemui/gui-components/checkbox-group, which registers
<gui-checkbox-group> and nothing else. To install the package and load the stylesheet, see
Installation.
The @golemui/gui-components/react components have typed props and an on* prop for each event. React 18 or later.
import { useState } from 'react';import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const choices = ['Cheese', 'Ham', 'Olives'];
export function ToppingsField() { const [toppings, setToppings] = useState([] as string[]);
return ( <GuiCheckboxGroup label="Toppings" name="toppings" options={choices} values={toppings} onGuiChange={(event) => setToppings(event.detail.value ?? [] as string[])} /> );}Add CUSTOM_ELEMENTS_SCHEMA to the component that uses the tags, and the stylesheet to styles in angular.json.
import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import type { GuiEventMap, GuiCheckboxGroupEvents } from '@golemui/gui-components';import '@golemui/gui-components/checkbox-group';
type ChangeEvent = GuiEventMap<typeof GuiCheckboxGroupEvents>['gui-change'];
@Component({ selector: 'app-toppings-field', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-checkbox-group label="Toppings" name="toppings" [options]="choices" [values]="toppings" (gui-change)="onChange($event)" ></gui-checkbox-group> `,})export class ToppingsFieldComponent { choices = ['Cheese', 'Ham', 'Olives'];
toppings = [] as string[];
onChange(event: Event) { this.toppings = (event as ChangeEvent).detail.value ?? [] as string[]; }}"styles": ["node_modules/@golemui/gui-components/lib/styles/index.css"]Tell Vue's compiler that gui-* tags are custom elements, and add the typings once for typed props and @gui-* handlers.
<script setup lang="ts">import { ref } from 'vue';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const choices = ['Cheese', 'Ham', 'Olives'];
const toppings = ref([] as string[]);</script>
<template> <gui-checkbox-group label="Toppings" name="toppings" :options.prop="choices" :values="toppings" @gui-change="toppings = $event.detail.value ?? [] as string[]" /></template>vue({ template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith('gui-') } },});import type {} from '@golemui/gui-components/vue';The page's stylesheet styles the gui-* elements, so it only reaches them outside a shadow root. Render the host component into the light DOM too, as below, or load the stylesheet into its shadow root.
import { LitElement, html } from 'lit';import { customElement, state } from 'lit/decorators.js';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const choices = ['Cheese', 'Ham', 'Olives'];
@customElement('toppings-field')export class ToppingsField extends LitElement { @state() private toppings = [] as string[];
protected override createRenderRoot() { return this; }
override render() { return html` <gui-checkbox-group label="Toppings" name="toppings" .options=${choices} .values=${this.toppings} @gui-change=${(event: CustomEvent) => (this.toppings = event.detail.value)} ></gui-checkbox-group> `; }}With any bundler, such as Vite. Import the element once, anywhere, and use the tag in your markup.
<gui-checkbox-group label="Toppings" name="toppings"></gui-checkbox-group>
<script type="module" src="./main.js"></script>import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const element = document.querySelector('gui-checkbox-group');element.options = ['Cheese', 'Ham', 'Olives'];
element.addEventListener('gui-change', (event) => { console.log(event.detail.value);});In HTML, options and values can also be JSON attributes, as in the examples below.
Properties
| Property | Type | Default | Description |
|---|---|---|---|
localeId
attribute locale-id | string | 'en' | BCP 47 locale for formatting and parsing, such as en-US or es. |
values | OptionValue[] | – | The values of the checked options, in the options' order. |
options | OptionInput[] | [] | The options: values, which are both the text and the value, { label, value } objects, or any objects read through label-field and value-field. |
labelField
attribute label-field | string | – | For options given as objects, the key of the text to show. |
valueField
attribute value-field | string | – | For options given as objects, the key of the value. |
direction | 'row' | 'column' | 'column' | Lays the options out in a row or a column. |
uid | string | – | The id of the element's control. The ids of its label, hint and errors derive from it. Optional: when it is not set, the element generates one from its tag name and a page-wide counter, e.g. gui-textinput-3. Generated ids depend on creation order, so a server-rendered element must set uid or its ids will not match after hydration. |
idPrefix
attribute id-prefix | string | – | Goes in front of every DOM id the element renders, so two elements with the same uid in different forms render different ids. GolemUI Forms sets it to the form's formName. Only ids and the references to them (for, aria-describedby…) take it: data-cy attributes and event details keep the bare uid. |
domId read-only, no attribute | string | – | The id of the element's control: uid, behind idPrefix when it is set. |
Form control properties
Every field has these, from the base class of the form controls.
| Property | Type | Default | Description |
|---|---|---|---|
value property only | unknown | – | values, under the name every form control takes its value by. |
name | string | – | The name the value is submitted under. Without it the element stays out of its form. Reflected, like a native control's: the form reads a single value's name from the attribute. |
label | string | – | The visible label, which also names the control for assistive technology. Without one the control has no accessible name; the date, time, range, tags and file fields warn about it in development builds. |
hint | string | – | Help text shown under the label and announced as the control's description. |
errors | string[] | [] | Error messages to show, typically from your own validation. They show as soon as they are set, unless touched is false. |
touched | boolean | – | Whether the user has interacted with the control. Leave it unset unless you validate on interaction: false holds errors back until it becomes true. |
required | boolean | false | The control needs a value: it is marked as required and, with a name, blocks submission. |
readOnly
attribute readonly | boolean | – | The value can be read and focused but not changed. |
disabled | boolean | – | Disabled by its own attribute or by a disabled <fieldset> around it. Setting the property sets the attribute, like a native control's. |
form read-only, no attribute | HTMLFormElement | null | – | The <form> the element belongs to, if any. |
validity read-only, no attribute | ValidityState | – | The element's validity, like a native control's. |
validationMessage read-only, no attribute | string | – | The message the browser shows for an invalid value. |
Methods
| Method | Description |
|---|---|
checkValidity(): boolean | – |
reportValidity(): boolean | – |
Events
Every event bubbles and is composed, so you can listen on any ancestor.
| Event | Description |
|---|---|
gui-input | The user checked or unchecked an option. detail.value is the new value. |
gui-change | The user committed the value. detail.value is the committed value. |
gui-blur | Focus left the group. |
Examples
Section titled “Examples”Options and values
Section titled “Options and values”options takes the list of options. As an attribute it is a JSON array; from JavaScript, set the
options property to an array. Each option is a string or a number, which is both its text and
its value, as above, or a { label, value } object, to show a text other than the value.
values lists the values of the checked options. Leave it unset to start with none checked. The
element keeps it in the options’ order, whatever order the user checks them in. The value
property is the same list, under the name every form control reads its value by.
import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const channels = [ { label: 'Email', value: 'email' }, { label: 'Text message', value: 'sms' }, { label: 'Push notification', value: 'push' },];
export function CheckboxGroupObjects() { return ( <GuiCheckboxGroup label="Notify me by" values={['email', 'push']} options={channels} /> );}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/checkbox-group';
@Component({ selector: 'app-checkbox-group-objects', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-checkbox-group label="Notify me by" [values]="checked" [options]="channels" ></gui-checkbox-group> `,})export class CheckboxGroupObjectsComponent { checked = ['email', 'push']; channels = [ { label: 'Email', value: 'email' }, { label: 'Text message', value: 'sms' }, { label: 'Push notification', value: 'push' }, ];}<script setup lang="ts">import type { Option } from '@golemui/gui-components';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const checked = ['email', 'push'];const channels: Option[] = [ { label: 'Email', value: 'email' }, { label: 'Text message', value: 'sms' }, { label: 'Push notification', value: 'push' },];</script>
<template> <gui-checkbox-group label="Notify me by" :values.prop="checked" :options.prop="channels" ></gui-checkbox-group></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const channels = [ { label: 'Email', value: 'email' }, { label: 'Text message', value: 'sms' }, { label: 'Push notification', value: 'push' },];
@customElement('checkbox-group-objects')export class CheckboxGroupObjects extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <gui-checkbox-group label="Notify me by" .values=${['email', 'push']} .options=${channels} ></gui-checkbox-group> `; }}<gui-checkbox-group label="Notify me by" values='["email", "push"]' options='[ { "label": "Email", "value": "email" }, { "label": "Text message", "value": "sms" }, { "label": "Push notification", "value": "push" } ]'></gui-checkbox-group>A value that matches no option checks nothing, and the element keeps it, after the options’ values. The user can’t see or change it.
Options from your data
Section titled “Options from your data”When your options are objects with other keys, such as records from an API, label-field names
the key of the text and value-field the key of the value. You don’t need to map them first.
These two win over the objects’ own label and value keys.
import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const languages = [ { name: 'English', code: 'en' }, { name: 'Spanish', code: 'es' }, { name: 'Japanese', code: 'ja' },];
export function CheckboxGroupFields() { return ( <GuiCheckboxGroup label="Subtitle languages" labelField="name" valueField="code" options={languages} /> );}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/checkbox-group';
@Component({ selector: 'app-checkbox-group-fields', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-checkbox-group label="Subtitle languages" label-field="name" value-field="code" [options]="languages" ></gui-checkbox-group> `,})export class CheckboxGroupFieldsComponent { languages = [ { name: 'English', code: 'en' }, { name: 'Spanish', code: 'es' }, { name: 'Japanese', code: 'ja' }, ];}<script setup lang="ts">import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const languages = [ { name: 'English', code: 'en' }, { name: 'Spanish', code: 'es' }, { name: 'Japanese', code: 'ja' },];</script>
<template> <gui-checkbox-group label="Subtitle languages" label-field="name" value-field="code" :options.prop="languages" ></gui-checkbox-group></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const languages = [ { name: 'English', code: 'en' }, { name: 'Spanish', code: 'es' }, { name: 'Japanese', code: 'ja' },];
@customElement('checkbox-group-fields')export class CheckboxGroupFields extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <gui-checkbox-group label="Subtitle languages" label-field="name" value-field="code" .options=${languages} ></gui-checkbox-group> `; }}<gui-checkbox-group label="Subtitle languages" label-field="name" value-field="code" options='[ { "name": "English", "code": "en" }, { "name": "Spanish", "code": "es" }, { "name": "Japanese", "code": "ja" } ]'></gui-checkbox-group>In a row
Section titled “In a row”The options stack in a column. direction="row" lays them out side by side, and wraps them onto
more lines when they don’t fit.
import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
export function CheckboxGroupRow() { return ( <GuiCheckboxGroup label="Delivery days" direction="row" values={['Mon', 'Wed']} options={days} /> );}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/checkbox-group';
@Component({ selector: 'app-checkbox-group-row', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-checkbox-group label="Delivery days" direction="row" [values]="checked" [options]="days" ></gui-checkbox-group> `,})export class CheckboxGroupRowComponent { checked = ['Mon', 'Wed']; days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];}<script setup lang="ts">import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const checked = ['Mon', 'Wed'];const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];</script>
<template> <gui-checkbox-group label="Delivery days" direction="row" :values.prop="checked" :options.prop="days" ></gui-checkbox-group></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
@customElement('checkbox-group-row')export class CheckboxGroupRow extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <gui-checkbox-group label="Delivery days" direction="row" .values=${['Mon', 'Wed']} .options=${days} ></gui-checkbox-group> `; }}<gui-checkbox-group label="Delivery days" direction="row" values='["Mon", "Wed"]' options='["Mon", "Tue", "Wed", "Thu", "Fri"]'></gui-checkbox-group>Disabled and read-only
Section titled “Disabled and read-only”A disabled group can’t be focused or changed, and a form doesn’t submit it. A readonly group
can be focused, but clicks and Space don’t change it, and a form submits its values.
import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
export function CheckboxGroupDisabledReadonly() { return ( <div className="gui-grid gui-grid--row"> <div className="gui-grid__cell"> <GuiCheckboxGroup label="Included in your plan" values={['Backups']} options={['Backups', 'Analytics']} disabled /> </div> <div className="gui-grid__cell"> <GuiCheckboxGroup label="Roles" values={['Editor']} options={['Viewer', 'Editor']} readOnly /> </div> </div> );}import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import '@golemui/gui-components/checkbox-group';
@Component({ selector: 'app-checkbox-group-disabled-readonly', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-checkbox-group label="Included in your plan" [values]="['Backups']" [options]="features" disabled ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-checkbox-group label="Roles" [values]="['Editor']" [options]="roles" readonly ></gui-checkbox-group> </div> </div> `,})export class CheckboxGroupDisabledReadonlyComponent { features = ['Backups', 'Analytics']; roles = ['Viewer', 'Editor'];}<script setup lang="ts">import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const features = ['Backups', 'Analytics'];const roles = ['Viewer', 'Editor'];</script>
<template> <div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-checkbox-group label="Included in your plan" :values.prop="['Backups']" :options.prop="features" :disabled="true" ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-checkbox-group label="Roles" :values.prop="['Editor']" :options.prop="roles" :readOnly="true" ></gui-checkbox-group> </div> </div></template>import { LitElement, html } from 'lit';import { customElement } from 'lit/decorators.js';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
@customElement('checkbox-group-disabled-readonly')export class CheckboxGroupDisabledReadonly extends LitElement { protected override createRenderRoot() { return this; }
override render() { return html` <div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-checkbox-group label="Included in your plan" .values=${['Backups']} .options=${['Backups', 'Analytics']} disabled ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-checkbox-group label="Roles" .values=${['Editor']} .options=${['Viewer', 'Editor']} readonly ></gui-checkbox-group> </div> </div> `; }}<div class="gui-grid gui-grid--row"> <div class="gui-grid__cell"> <gui-checkbox-group label="Included in your plan" values='["Backups"]' options='["Backups", "Analytics"]' disabled ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-checkbox-group label="Roles" values='["Editor"]' options='["Viewer", "Editor"]' readonly ></gui-checkbox-group> </div></div>Errors
Section titled “Errors”errors takes a list of messages from your own validation, and shows them under the group. Set
the errors property from a gui-change listener to validate as the user works, such as a limit
on how many options they pick. Check a third option.
import { useState } from 'react';import type { OptionValue } from '@golemui/gui-components';import { GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const topics = ['Design', 'Engineering', 'Marketing', 'Sales'];
export function CheckboxGroupValidation() { const [values, setValues] = useState<OptionValue[]>([]); const errors = values.length > 2 ? ['Pick at most two interests.'] : [];
return ( <GuiCheckboxGroup id="interests" label="Interests" hint="Pick up to two." options={topics} values={values} errors={errors} onGuiChange={(event) => setValues(event.detail.value ?? [])} /> );}import { Component, CUSTOM_ELEMENTS_SCHEMA, signal } from '@angular/core';import type { GuiCheckboxGroupEvents, GuiEventMap,} from '@golemui/gui-components';import '@golemui/gui-components/checkbox-group';
type CheckboxGroupEvent<K extends keyof typeof GuiCheckboxGroupEvents> = GuiEventMap<typeof GuiCheckboxGroupEvents>[K];
@Component({ selector: 'app-checkbox-group-validation', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <gui-checkbox-group id="interests" label="Interests" hint="Pick up to two." [options]="topics" [errors]="errors()" (gui-change)="onChange($event)" ></gui-checkbox-group> `,})export class CheckboxGroupValidationComponent { topics = ['Design', 'Engineering', 'Marketing', 'Sales']; errors = signal<string[]>([]);
onChange(event: Event) { const { value } = (event as CheckboxGroupEvent<'gui-change'>).detail; this.errors.set( (value ?? []).length > 2 ? ['Pick at most two interests.'] : [], ); }}<script setup lang="ts">import { ref } from 'vue';import type { OptionValue } from '@golemui/gui-components';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const topics = ['Design', 'Engineering', 'Marketing', 'Sales'];const errors = ref<string[]>([]);
function onChange(values: OptionValue[] | undefined) { errors.value = (values ?? []).length > 2 ? ['Pick at most two interests.'] : [];}</script>
<template> <gui-checkbox-group id="interests" label="Interests" hint="Pick up to two." :options.prop="topics" :errors.prop="errors" @gui-change="onChange($event.detail.value)" ></gui-checkbox-group></template>import { LitElement, html } from 'lit';import { customElement, state } from 'lit/decorators.js';import type { GuiCheckboxGroupEvents, GuiEventMap,} from '@golemui/gui-components';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
type CheckboxGroupEvent<K extends keyof typeof GuiCheckboxGroupEvents> = GuiEventMap<typeof GuiCheckboxGroupEvents>[K];
const topics = ['Design', 'Engineering', 'Marketing', 'Sales'];
@customElement('checkbox-group-validation')export class CheckboxGroupValidation extends LitElement { @state() private errors: string[] = [];
protected override createRenderRoot() { return this; }
private onChange(event: CheckboxGroupEvent<'gui-change'>) { this.errors = (event.detail.value ?? []).length > 2 ? ['Pick at most two interests.'] : []; }
override render() { return html` <gui-checkbox-group id="interests" label="Interests" hint="Pick up to two." .options=${topics} .errors=${this.errors} @gui-change=${this.onChange} ></gui-checkbox-group> `; }}<gui-checkbox-group id="interests" label="Interests" hint="Pick up to two." options='["Design", "Engineering", "Marketing", "Sales"]'></gui-checkbox-group>
<script type="module"> const interests = document.querySelector('#interests');
interests.addEventListener('gui-change', (event) => { interests.errors = event.detail.value.length > 2 ? ['Pick at most two interests.'] : []; });</script>In a form
Section titled “In a form”With a name, <gui-checkbox-group> submits one entry per checked option under that name, like
native checkboxes that share a name, so read them with FormData.getAll(). It submits nothing
while none is checked. required blocks the submit until the user checks at least one. Submit
the form below, then check two options and submit again.
import { useState, type SubmitEvent } from 'react';import { GuiButton, GuiCheckboxGroup } from '@golemui/gui-components/react';import '@golemui/gui-components/index.css';
const toppings = [ { label: 'Cheese', value: 'cheese' }, { label: 'Ham', value: 'ham' }, { label: 'Olives', value: 'olives' },];
export function CheckboxGroupNativeForm() { const [result, setResult] = useState('');
const onSubmit = (event: SubmitEvent<HTMLFormElement>) => { event.preventDefault(); // getAll: the group submits one entry per checked option. const checked = new FormData(event.currentTarget).getAll('toppings'); setResult(`Submitted ${JSON.stringify({ toppings: checked })}`); };
return ( <form id="pizza" onSubmit={onSubmit}> <div className="gui-grid"> <div className="gui-grid__cell"> <GuiCheckboxGroup label="Toppings" name="toppings" required options={toppings} /> </div> <div className="gui-grid__cell"> <GuiButton type="submit" label="Order" /> </div> </div> <p id="pizza-result" role="status"> {result} </p> </form> );}import { Component, CUSTOM_ELEMENTS_SCHEMA, signal } from '@angular/core';import '@golemui/gui-components/button';import '@golemui/gui-components/checkbox-group';
@Component({ selector: 'app-checkbox-group-native-form', schemas: [CUSTOM_ELEMENTS_SCHEMA], template: ` <form id="pizza" #form (submit)="onSubmit($event, form)"> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-checkbox-group label="Toppings" name="toppings" required [options]="toppings" ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Order"></gui-button> </div> </div> <p id="pizza-result" role="status">{{ result() }}</p> </form> `,})export class CheckboxGroupNativeFormComponent { toppings = [ { label: 'Cheese', value: 'cheese' }, { label: 'Ham', value: 'ham' }, { label: 'Olives', value: 'olives' }, ];
result = signal('');
onSubmit(event: SubmitEvent, form: HTMLFormElement) { event.preventDefault(); // getAll: the group submits one entry per checked option. const toppings = new FormData(form).getAll('toppings'); this.result.set(`Submitted ${JSON.stringify({ toppings })}`); }}<script setup lang="ts">import { ref } from 'vue';import type { Option } from '@golemui/gui-components';import '@golemui/gui-components/button';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const toppings: Option[] = [ { label: 'Cheese', value: 'cheese' }, { label: 'Ham', value: 'ham' }, { label: 'Olives', value: 'olives' },];
const result = ref('');
function onSubmit(event: SubmitEvent) { if (!(event.currentTarget instanceof HTMLFormElement)) return; // getAll: the group submits one entry per checked option. const checked = new FormData(event.currentTarget).getAll('toppings'); result.value = `Submitted ${JSON.stringify({ toppings: checked })}`;}</script>
<template> <form id="pizza" @submit.prevent="onSubmit"> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-checkbox-group label="Toppings" name="toppings" :required="true" :options.prop="toppings" ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Order"></gui-button> </div> </div> <p id="pizza-result" role="status">{{ result }}</p> </form></template>import { LitElement, html } from 'lit';import { customElement, query, state } from 'lit/decorators.js';import '@golemui/gui-components/button';import '@golemui/gui-components/checkbox-group';import '@golemui/gui-components/index.css';
const toppings = [ { label: 'Cheese', value: 'cheese' }, { label: 'Ham', value: 'ham' }, { label: 'Olives', value: 'olives' },];
@customElement('checkbox-group-native-form')export class CheckboxGroupNativeForm extends LitElement { @query('#pizza') private form!: HTMLFormElement; @state() private result = '';
protected override createRenderRoot() { return this; }
private onSubmit(event: SubmitEvent) { event.preventDefault(); // getAll: the group submits one entry per checked option. const checked = new FormData(this.form).getAll('toppings'); this.result = `Submitted ${JSON.stringify({ toppings: checked })}`; }
override render() { return html` <form id="pizza" @submit=${this.onSubmit}> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-checkbox-group label="Toppings" name="toppings" required .options=${toppings} ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Order"></gui-button> </div> </div> <p id="pizza-result" role="status">${this.result}</p> </form> `; }}<form id="pizza"> <div class="gui-grid"> <div class="gui-grid__cell"> <gui-checkbox-group label="Toppings" name="toppings" required options='[ { "label": "Cheese", "value": "cheese" }, { "label": "Ham", "value": "ham" }, { "label": "Olives", "value": "olives" } ]' ></gui-checkbox-group> </div> <div class="gui-grid__cell"> <gui-button type="submit" label="Order"></gui-button> </div> </div> <p id="pizza-result" role="status"></p></form>
<script type="module"> const form = document.querySelector('#pizza');
form.addEventListener('submit', (event) => { event.preventDefault(); // getAll: the group submits one entry per checked option. const toppings = new FormData(form).getAll('toppings'); document.querySelector('#pizza-result').textContent = `Submitted ${JSON.stringify({ toppings })}`; });</script>The checkboxes inside stay out of the form: the element submits the values itself.
How the elements submit, validate and reset is in Native forms.
Styling
Section titled “Styling”Anatomy
Section titled “Anatomy”<gui-checkbox-group> renders into the light DOM, so you can style every part with plain CSS.
These are the parts and their public classes:
<gui-checkbox-group class="gui-field"> <span class="gui-label" id="toppings_label"> <span class="gui-label__text"> Toppings<span aria-hidden="true"> *</span> </span> <div class="gui-widget-hint" id="toppings_hint" aria-hidden="true"> Pick any you like. </div> </span> <div role="group" class="gui-widget" id="toppings" aria-labelledby="toppings_label toppings_required" aria-describedby="toppings_hint" > <span class="gui-visually-hidden" id="toppings_required">required</span> <label for="toppings_0"> <input type="checkbox" id="toppings_0" data-group="toppings" form="toppings_none" value="cheese" aria-describedby="toppings_hint" aria-invalid="true" aria-errormessage="toppings_errors" /> Cheese </label> <label for="toppings_1"> <input type="checkbox" id="toppings_1" data-group="toppings" form="toppings_none" value="ham" aria-describedby="toppings_hint" aria-invalid="true" aria-errormessage="toppings_errors" /> Ham </label> <!-- One label and checkbox per option. --> </div> <div class="gui-validator" id="toppings_errors" role="alert"> <div class="gui-validator__error">Pick a topping.</div> </div></gui-checkbox-group>| Class | Part |
|---|---|
gui-field | The element itself. Lines its parts up with the fields next to it in a gui-grid row. |
gui-label | The group’s label, with the text and the hint. |
gui-label__text | The label text and the required marker. |
gui-widget-hint | The hint. |
gui-widget | The group, with a <label> and a checkbox per option. |
gui-widget--horizontal | On the group with direction="row": lays the options out in a row. |
gui-validator | The errors container. It is always there, so the alert role announces new errors. |
gui-validator__error | One error message. |
The options have no class of their own: select them as gui-checkbox-group label and
gui-checkbox-group input. The ids derive from uid, or from a generated id such as
gui-checkbox-group-3 when you don’t set one. Select by class or by tag, not by id.
Tokens
Section titled “Tokens”The group draws its checkboxes as <gui-checkbox> does, and
reads the same --gui-checkbox-* tokens, so one setting styles both. Set them on :root to
change every checkbox, or on any element to change the checkboxes inside it:
| Token | What it styles |
|---|---|
--gui-checkbox-size | The width and height of each box. Defaults to 1rem. |
--gui-checkbox-radius | The boxes’ corner radius. Defaults to --gui-radius-sm. |
--gui-checkbox-bg | The boxes’ background. Defaults to --gui-bg-surface. |
--gui-checkbox-border | The boxes’ border. Defaults to --gui-border-strong. |
--gui-checkbox-tick | The tick. Defaults to --gui-intent-primary. |
--gui-checkbox-gap | The space between a box and its text. Defaults to --gui-space-2. |
--gui-text-default | The label and the options’ text. |
--gui-font-family | The font. |
--gui-font-sm | The text size of the label and the options. |
--gui-font-xs | The text size of the hint and the errors. |
--gui-text-secondary | The hint. |
--gui-border-focus | The border of the focused box. |
--gui-shadow-focus | The focus ring. |
--gui-intent-error | The boxes’ border and the messages when there are errors. |
--gui-shadow-focus-error | The focus ring when there are errors. |
/* Bigger boxes, with more room before their text, in every checkbox. */:root { --gui-checkbox-size: 1.25rem; --gui-checkbox-gap: 0.75rem;}To restyle beyond the tokens, see Overriding styles; for dark mode and the Clay theme, see Themes and dark mode.
Accessibility
Section titled “Accessibility”- Group. The checkboxes sit in an element with the
grouprole, named by thelabelthrougharia-labelledby. Without a label the group has no accessible name. Each checkbox is named by its option’s text. - Description. The
hintis the group’s description, througharia-describedby. - Errors. While errors show, the checkboxes have
aria-invalid="true"and point at them witharia-errormessage, and screen readers announce new errors as they appear. - Required. A group has no required state of its own, and
aria-requiredon a checkbox would mean that box must be checked. Arequiredgroup adds “required” to its name instead, in a text hidden on screen. Translate it with therequiredGroupmessage, see i18n. - Read-only.
readonlysetsaria-readonlyon each checkbox. They stay in the tab order. - Tab stops. Each checkbox is a stop in the tab order, as native checkboxes are.
gui-blurfires only when focus leaves the group: moving from one checkbox to another doesn’t fire it.
| Key | Action |
|---|---|
| Tab | Moves focus to the next checkbox, and out of the group. |
| Space | Checks or unchecks the focused one, and fires gui-change. |
In a read-only group Space does nothing.
What every element shares, such as translating the browser messages, is in Accessibility.