---
description: FastHTML constructors for native buttons, inputs, groups, toolbars, copy
  actions, toggles, sliders, fields, and fieldsets styled from browser and ARIA states
output-file: controls.html
title: controls

---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

These constructors return native HTML form controls marked with opt-in attributes such as `btn` or `input`. The browser manages control state. Shared CSS applies those states through pseudo-classes (`:disabled`, `:user-invalid`) and ARIA attributes (`aria-busy`, `aria-pressed`). Plain FastHTML `Button` and [`Input`](controls.md#input) elements remain unstyled. The Python constructors emit markup only and include no stylesheets or browser scripts.

```python
from fasthtml.common import *
from answerui.demo import demo
from answerui.registry import reg
from fastcore.test import *
from fastlucide.icons import X
```

## Btn

Buttons are raised at rest and sunken while pressed. Pressing shifts the label, bevels, and shadows without changing outer dimensions. A row of buttons stays aligned regardless of which ones are pressed.

Three ARIA attributes hold a button in its sunken state without shifting the label: `aria-busy="true"` for an in-flight request, `aria-pressed="true"` for a latched toggle, and `aria-expanded="true"` for an open popover or menu. Each variant controls that appearance through `--ui-held-face` and `--ui-held-shadow`.

A busy button fades its label and shows a centred spinner without resizing. Because `aria-busy="true"` changes appearance only, users can still click a busy button. Set `disabled` to prevent activation.

When a button triggers an htmx request, htmx adds the `htmx-request` class while the request runs. The busy appearance waits for `--busy-delay` (default `200ms`) to avoid flashing on fast requests. Server-set `aria-busy="true"` appears immediately. When a form triggers the request, htmx adds `htmx-request` to the form instead of the button. Set `hx-indicator` on the form to target the button.

A disabled button is flat and faded with no shadow while retaining its variant colour. Re-enabling it restores the raised appearance.

The default `primary` variant uses the accent colour. `variant='secondary'` uses the neutral surface colour with a hairline border. `variant='quiet'` has no background, border, or shadow at rest and inherits the parent text colour. Hovering a quiet button applies `--tint` (8% alpha). Pressing or holding it applies a 12% tint.

Pass `size='sm'` or `size='lg'` to set `btn-size` for compact or prominent actions (`None` uses the default size).

Pass `href` to render an `<a>` styled as a button, with the same variants, sizes, and `icon` option (omitting `type`). Because links have no native `disabled` state, `:disabled` styling does not apply to them. Handwritten `<a btn href="...">` elements match the same rules.

---

### Btn

```python
def Btn(
    *c, variant:str='primary', size=None, href=None, type:str='button', icon:bool=False, **attrs
):
```

*A raised action, latched by aria-pressed and sunken while busy or expanded*

Each variant, size, and state in a wrapping cluster: default, secondary, quiet, a link, small and large sizes, danger and success tones, disabled, busy, and latched:

```python
Btn.demo()
```

Passing `href` emits an `<a>` without `type`, and `size` sets `btn-size` only when given:

```python
link = Btn('Sign up', href='/signup', variant='secondary', size='lg')
test_eq(link.tag, 'a')
assert 'type' not in link.attrs
test_eq(link.attrs['btn-size'], 'lg')
assert Btn('Save').attrs.get('btn-size') is None
to_xml(link)
```

```output
'<a href="/signup" btn btn-variant="secondary" btn-size="lg">Sign up</a>'
```

Custom variants can override resting padding (`--ui-pad-block`, `--ui-pad-inline`) or `--relief` without redefining the pressed state. Below, `compact` tightens padding and `flat` sets `--relief: 0`. Both variants are registered on [`Btn`](controls.md#btn) for this notebook rather than built in. `doc(Btn)` lists them while they remain registered. To reduce depth across an entire application, set `:root { --relief: .5; }`.

```python
Btn.variant('compact', '--ui-pad-block: var(--space-3); --ui-pad-inline: var(--space-2);', doc='Tighter padding.')
Btn.variant('flat', '--relief: 0;', doc='No rims, shadows, or displacement.')
```

```output
Btn.flat [app] :is([btn])[flat]: No rims, shadows, or displacement.
```

Flat buttons show their colour states without bevels, shadows, or label shift. The two Pin buttons compare unselected (`aria-pressed="false"`) and selected (`aria-pressed="true"`):

```python
demo(Cluster(
    Btn('Compact', compact=True), Btn('Flat', flat=True),
    Btn('Pin', variant='secondary', flat=True, aria_pressed='false'),
    Btn('Pin', variant='secondary', flat=True, aria_pressed='true'),
    cls='gap-2'))
```

Pass `icon=True` for an icon-only button to make its horizontal padding match its vertical padding (`--ui-pad-inline: var(--ui-pad-block)`). Always supply an `aria-label` because an icon has no accessible name. Buttons containing both an icon and text use standard button padding.

Three square icon-only close buttons (`primary`, `secondary`, `quiet`) beside a labelled icon button and a text-only button:

```python
close = [Btn(X(), icon=True, aria_label='Close'), Btn(X(), icon=True, aria_label='Close', variant='secondary'),
    Btn(X(), icon=True, aria_label='Close', variant='quiet')]
demo(Cluster(*close, Btn(X(), 'Close', variant='secondary'), Btn('Save'), cls='gap-2'))
```

## Text controls

Text controls use inverted bevel lighting (`--bevel-in` and `--sunken`) to look recessed into the page like a well. Disabled controls flatten to a muted background without the sunken shadow. [`Input`](controls.md#input), [`Textarea`](controls.md#textarea), and [`Select`](controls.md#select) add the `input`, `textarea`, and `select` marker attributes. Handwritten HTML with the same attributes matches the same CSS rules. [`Input`](controls.md#input) rejects `type='checkbox'`, `type='radio'`, and `type='range'` so well styling is not applied by mistake; use [`Checkbox`](controls.md#checkbox), [`Radio`](controls.md#radio), or [`Range`](controls.md#range) instead, and use FastHTML's unmarked [`Input`](controls.md#input) for file pickers or button-type inputs.

Number inputs (`type="number"`) hide browser spin buttons while keeping keyboard arrow stepping.

Invalid controls show a danger border colour computed from `--hue-danger`. That rule matches both `:user-invalid` (set by the browser after interaction) and server-set `aria-invalid="true"`:

---

### Select

```python
def Select(
    *c, chars=None, **attrs
):
```

*A native select styled as a well*

---

### Textarea

```python
def Textarea(
    *c, chars=None, **attrs
):
```

*A text area that grows with its content*

---

### Input

```python
def Input(
    chars=None, **attrs
):
```

*A text-like input styled as a well*

Each text control on its own, at rest, and disabled:

```python
Input.demo()
```

```python
for t, alt in _input_alts.items(): test_fail(lambda t=t: Input(type=t), exc=ValueError, contains=alt)
```

Add the `input` attribute to style a non-control element as a well, such as a read-only block or a `div` hosting a third-party widget:

```python
demo(Stack(Div('A widget mounts here', input=True), Input(placeholder='A text input, for comparison', aria_label='Comparison')))
```

## Enabling a button

Render a submit button `disabled` with an `enable` attribute to enable it automatically when form conditions are met. Set `enable="changed"` to wait until any control differs from its initial rendered value. Set `enable="valid"` to wait until the form passes native validation, or `enable="changed valid"` to require both.

The shared form handler compares each control against its browser default (`defaultValue`, `defaultChecked`, or `defaultSelected`) without storing a separate snapshot. Resetting the form disables the button again. Forms swapped in by htmx work the same way because the browser treats their rendered values as defaults.

Change the name or enter a valid required email address to enable Save. Clicking Reset restores the initial values and disables Save again:

```python
demo(Form(Input(name='name', value='Ada', aria_label='Display name'), Input(name='email', type='email', required=True, placeholder='Email', aria_label='Email'),
    Cluster(Btn('Save', type='submit', disabled=True, enable='changed valid'), Btn('Reset', type='reset', variant='secondary')), stack=True, style='inline-size: 24rem'))
```

## Group

[`Group`](controls.md#group) wraps related controls in a `div[group]` with shared inner borders and rounded outer corners. Passing `inset=True` sets `group-variant="inset"` to render the whole group as a single well with the action button inside.

[`Toolbar`](controls.md#toolbar) wraps controls in a `div[toolbar][group]` with `role="toolbar"`. The shared toolbar controller provides a single Tab stop and moves focus across enabled commands with Left, Right, Home, and End. Set `aria-pressed` on the server to mark latched toggles. Use native radios for an exclusive form choice.

---

### Toolbar

```python
def Toolbar(
    *controls, **attrs
):
```

*A row of commands with arrow-key navigation*

---

### Affix

```python
def Affix(
    *c, **attrs
):
```

*Static prefix or suffix text or icon attached to a control inside [`Group`](controls.md#group)*

---

### Group

```python
def Group(
    *c, inset:bool=False, **attrs
):
```

*Controls sharing an edge; inset places actions inside the input's well*

A standard group (name input with Create button) and an inset group (editable name with Save button). Enter a name in the first to enable Create, or edit the second to enable Save:

```python
Group.demo()
```

A pager toolbar and a toggle bar labelled with `aria-label`, with one button latched and one disabled. In production the server sets `aria-pressed`. Here a demo-only rule toggles it on click:

```python
reg.rule(name='demo-toolbar-toggle', sel='[toolbar]', on={('& button[aria-pressed]', 'click'): r"el.setAttribute('aria-pressed', String(el.getAttribute('aria-pressed') !== 'true'))"},
    doc='Demo only: flips aria-pressed in place of the server.')
```

```output
demo-toolbar-toggle [app] [toolbar]: Demo only: flips aria-pressed in place of the server.
```

```python
Toolbar.demo()
```

## Copy

[`Copy`](controls.md#copy) renders a `quiet` button (icon-only by default, with `aria-label="Copy"`) that copies text to the clipboard. Pass `copyfor` with the `id` of a target element to copy a form control's `value` or any other element's `textContent`. Pass `copy` to copy a fixed string instead.

For `1.5s` after clicking, the click handler sets the `copied` attribute on the button and swaps its icon to a check mark. If the button has an `aria-label`, the handler temporarily sets it to `'Copied'` so screen readers announce the confirmation. Buttons with visible text labels are left unchanged. The Clipboard API requires a secure context (HTTPS or localhost).

---

### Copy

```python
def Copy(
    *c, copyfor=None, copy=None, variant:str='quiet', **attrs
):
```

*Copy fixed text or an element's value or text to the clipboard*

An API key inside a read-only inset group with an icon-only copy button, followed by a command beside a labelled `secondary` copy button. Click either button to test the check state:

```python
Copy.demo()
```

## Click to edit

Use `Btn(..., variant='editable')` for values that are read far more often than edited. It renders a full-width button with the same padding and corner radius as a text well, bordered by a dashed hairline (`--n`) instead of a sunken surface. No input exists until the user clicks. Visibility does not depend on hover. On click, the application fetches and swaps in either a single input or a multi-field form. Inside a form, keep `type="button"` (the default on [`Btn`](controls.md#btn)). Set `aria-label` to describe the edit action because the button's visible text is the current value.

The demo below uses a client-only rule to swap each value with its edit form. Click the name to open an inset input with Save, or click the schedule to edit day and time. Submitting updates the displayed value. Pressing Escape or clicking outside cancels and restores the previous value:

```python
reg.rule(name='demo-editable', sel='[editable-demo]', on={
    ('& button[btn-variant=editable]', 'click'): r"const p = el.closest('[editable-demo]'); p.firstElementChild.hidden = true; p.lastElementChild.hidden = false; p.querySelector('input, select').focus()",
    ('& form', 'submit'): r"e.preventDefault(); const p = el.closest('[editable-demo]'); p.querySelector('button[btn-variant=editable]').textContent = el.dataset.text.replace(/\{(\w+)\}/g, (_, n) => el.elements[n].value); el.hidden = true; p.firstElementChild.hidden = false",
    ('& form', 'keydown'): r"if (e.key === 'Escape') { el.reset(); el.hidden = true; el.previousElementSibling.hidden = false }",
    (':root', 'pointerdown'): r"for (const f of document.querySelectorAll('[editable-demo] > form:not([hidden])')) if (!f.contains(e.target)) { f.reset(); f.hidden = true; f.previousElementSibling.hidden = false }",
}, doc='Demo only: swaps the value for its form and back in place of the server; a click outside or Escape cancels.')

def _editable_demo(value, form, text, **attrs):
    "An editable value and the hidden form that edits it; `text` is the template that turns the form's fields into the new value"
    return Div(Btn(value, variant='editable', **attrs), Form(form, data_text=text, hidden=True), editable_demo=True)
```

```python
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
demo(Stack(
    _editable_demo('Untitled-1', Group(Input(name='name', value='Untitled-1', aria_label='Name'), Btn('Save', type='submit', disabled=True, enable='changed valid'), inset=True),
        '{name}', aria_label='Rename Untitled-1'),
    _editable_demo('Every Monday at 09:00', Group(Select(*[Option(d, selected=d == 'Monday') for d in days], name='day', aria_label='Day'),
        Input(type='time', name='time', value='09:00', aria_label='Time'), Btn('Save', type='submit', disabled=True, enable='changed valid')),
        'Every {day} at {time}', aria_label='Change the schedule'),
    style='inline-size: 24rem'))
```

## Switch

Use [`Switch`](controls.md#switch) for immediate on/off settings rather than deferred form submissions. [`Switch`](controls.md#switch) returns a native `<input type="checkbox" role="switch" switch>`, letting the browser handle state, keyboard input, and accessibility announcements. CSS styles the track as a recessed well with a raised thumb that slides across on `--color-accent` when checked. Inside [`Field`](controls.md#field), the control appears before its label just like a checkbox:

---

### Switch

```python
def Switch(
    **attrs
):
```

*A checkbox with the switch role*

Off, on, and disabled:

```python
Switch.demo()
```

## Checkbox and radio

[`Checkbox`](controls.md#checkbox) and [`Radio`](controls.md#radio) return native `<input type="checkbox" checkbox>` and `<input type="radio" radio>` elements. Shared CSS sets `appearance: none` to style each as a small recessed well with `--sunken` shadow and no bevel rims (reverting to native `appearance: auto` under `forced-colors: active`):

---

### Checkbox

```python
def Checkbox(
    **attrs
):
```

*A checkbox styled as a small well*

---

### Radio

```python
def Radio(
    **attrs
):
```

*A radio button styled as a small well*

Unchecked, checked, disabled, and checked and disabled:

```python
Checkbox.demo()
```

Radios in a group, unchecked, checked, and checked and disabled:

```python
Radio.demo()
```

## Range

[`Range`](controls.md#range) returns an `<input type="range" range>` styled as a recessed track with a raised thumb. The shared browser script computes `--ui-range-fill` from `value`, `min` (default `0`), and `max` (default `100`) on mount, on `input` or `change`, and after form reset. Scripts that assign `value` programmatically must dispatch an `input` event to refresh the track fill.

The shared stylesheet (`03_controls`) defines the WebKit and Firefox track and thumb rules once. [`Range`](controls.md#range) adds only the `range` attribute.

---

### Range

```python
def Range(
    **attrs
):
```

*A slider with a filled track and raised thumb*

Four sliders below show default (`35`), disabled (`65`), `0` to `10` (`8`), and `-10` to `0` (`-5`). The last slider confirms that `max=0` acts as an explicit upper bound rather than falling back to `100`:

```python
Range.demo()
```

## Field

[`Field`](controls.md#field) pairs a control with its `<label>` plus optional `hint` and `error` messages so assistive technology announces them together. If the control lacks an `id`, [`Field`](controls.md#field) generates one and links the `<label>` via `for`. [`Field`](controls.md#field) sets `field-inline` on switches, checkboxes, and radios so the control appears before its label text. Because that inline label uses `justify-self: start`, clicking empty space to the right of the text does not toggle the control.

`hint` and `error` render as `<small>` elements below the control, with their ids appended to the control's `aria-describedby`. Passing `error` styles the message with `ui-tone="danger"` and sets `aria-invalid="true"` on the control. Validation rules stay in the application. [`Field`](controls.md#field) only displays the message you pass.

---

### Field

```python
def Field(
    label, control, hint=None, error=None, **attrs
):
```

*A labelled control with optional help and error text*

Native browser validation bubbles appear only on submit and never show when `enable="valid"` disables the submit button. Instead, the shared field handler renders the browser's `validationMessage` inside `<small validation ui-tone="danger">` under `[field]` when the user leaves a `:user-invalid` control or when submission fails. On a failed submit, every invalid field displays its message and the handler focuses the first invalid control.

While displayed, the validation element's `id` is added to the control's `aria-describedby`. Once the value becomes valid, the handler removes the `<small validation>` element and strips its `id` from `aria-describedby`. Server-rendered `error` messages passed to [`Field`](controls.md#field) have no `validation` attribute and are left untouched by the client handler.

For form-level server errors, render `<small validation ui-tone="danger">` (`Small(msg, ui_tone='danger', validation=True)`) inside the form outside any `[field]`. Editing any control in the form removes that form-level message immediately. A `<small validation>` element inside a `[field]` is cleared only when that field's control becomes valid.

All control types in one form. The Username field shows both a `hint` and a server-supplied `error`. Enter an invalid address in Email and move focus away to trigger client validation:

```python
Field.demo()
```

Extra keyword arguments (and variants declared on [`Field`](controls.md#field)) are placed on the outer `div[field]`. Existing attributes on the control remain intact. Any existing `aria-describedby` ids precede the generated hint and error ids:

```python
notes = Textarea(name='notes', aria_describedby='notes-policy')
field = Field('Notes', notes, hint='Keep it brief.', error='Please remove the account number.', compact=True)
assert isinstance(notes.id, str)
test_eq(field.children[0].get('for'), notes.id)
assert notes.attrs['aria-invalid'] == 'true'
assert notes.attrs['aria-describedby'].split() == ['notes-policy', *(o.id for o in field.children[2:])]
test_eq(field.attrs['compact'], True)
notes.attrs
```

```output
{'textarea': True,
 'name': 'notes',
 'aria-describedby': 'notes-policy _dJMevOKvQmmuLBzCcgsN_Q _bQHv4kyARGm1BFgQH5IYjA',
 'id': '_TjudwZL5RgmmI-9IhcCCvg',
 'aria-invalid': 'true'}
```

```python
amt = Input(name='amt', inputmode='decimal', chars=6, style='text-align: end')
test_eq(amt.attrs['chars'], True)
assert '--ui-chars: 6;' in amt.attrs['style'] and 'text-align: end' in amt.attrs['style']
gf = Field('Amount', Group(Affix('US$'), amt, Btn('Top up', type='submit')), hint='Whole dollars.')
test_eq(gf.children[0].attrs['for'], amt.id)
assert 'aria-describedby' in amt.attrs
```

## Fieldset

[`Fieldset`](controls.md#fieldset) renders a native `<fieldset fieldset>` with a hairline border and inner padding (`--space`) around a `<legend>`. Pass `stack=True` or another layout attribute to space the fields inside:

---

### Fieldset

```python
def Fieldset(
    *c, **attrs
):
```

*A bordered group of fields under a legend*

Two checkbox fields under a legend:

```python
Fieldset.demo()
```

To show a field only while a checkbox is checked, set `reveals` on the checkbox to the target element's `id`. Match the target's initial `hidden` attribute to the checkbox's initial checked state. On each `input` or `change` event, the shared handler sets `target.hidden = !checkbox.checked`:

```python
demo(Form(Field('Set a monthly limit', Checkbox(name='limit_on', reveals='limit')),
    Field('Monthly limit (US$)', Input(name='limit', type='number', value=200), id='limit', hidden=True), stack=True))
```
