Skip to content

Switch

A control that slides between on and off, bound to a boolean form field.

Switch
Thymeleaf source
<sl:label><sl:switch th:field="*{airplaneMode}"/>Airplane mode</sl:label>
Rendered HTML
<label class="label">
<input type="checkbox" role="switch" class="switch" name="airplaneMode">
Airplane mode
</label>
  • A setting that is on or off, such as email notifications or a public profile.
  • A feature in a settings page, with a description next to it in a field.

Use something else for:

  • Accepting terms, or picking several options: a checkbox.
  • A button that is pressed or not, such as Bold: a toggle.

A switch is a checkbox with role="switch", so a screen reader announces it as on or off and a form submits it as a checkbox. th:field on a boolean field works as it does on the checkbox, including the numbered id: put the switch inside its label.

Use a switch for a setting that takes effect as it is, and a checkbox for a choice the user confirms by submitting a form.

Sizes
Thymeleaf source
<sl:label><sl:switch size="sm" name="compact" checked/>Small</sl:label>
<sl:label><sl:switch name="regular" checked/>Default</sl:label>
Rendered HTML
<label class="label">
<input type="checkbox" role="switch" class="switch" data-size="sm" name="compact" checked>
Small
</label>
<label class="label">
<input type="checkbox" role="switch" class="switch" name="regular" checked>
Default
</label>
Invalid
Thymeleaf source
<sl:label><sl:switch th:field="*{marketing}"/>Marketing emails</sl:label>
Rendered HTML
<label class="label">
<input type="checkbox" role="switch" class="switch" name="marketing" aria-invalid="true">
Marketing emails
</label>

Track and thumb fade together, and so does the label. A disabled switch is not submitted, so Spring leaves out the hidden marker input it adds for a th:field checkbox: the bound value stays as it was.

Disabled
Thymeleaf source
<sl:label><sl:switch name="sso" checked disabled/>Single sign-on (managed by your organisation)</sl:label>
<sl:label><sl:switch name="betaFeatures" disabled/>Beta features (not in your plan)</sl:label>
Rendered HTML
<label class="label">
<input type="checkbox" role="switch" class="switch" name="sso" checked disabled>
Single sign-on (managed by your organisation)
</label>
<label class="label">
<input type="checkbox" role="switch" class="switch" name="betaFeatures" disabled>
Beta features (not in your plan)
</label>
AttributeValuesDefaultDescription
sizesm defaultdefaultSize of the switch.

Every prop can also be set from an expression: th:size="${...}". Any other attribute passes through to the rendered element, and class is appended.

The classes and attributes your own CSS can select to restyle the component, as explained in your own CSS rules.

Parts

ClassElement
.switch<input>

Props

PropSelectorValues
size.switch[data-size="…"]
.switch:not([data-size])
sm
default (default)

States

SelectorValues
.switch[aria-invalid="…"]true