DocsForms & drafts
Get started

Search Subtly documentation

Search by a task, helper name or framework.

Forms & drafts

focusInvalid()

Move to the first invalid field.

Try the example

Submit the empty project form. Focus moves to the first missing field. Fill the title, submit again and focus moves to the email field.

Both fields are required. Nothing is submitted.

Actual npm package · local demonstration

Add it to your project

  1. Copy the HTML. Place the markup inside the component where this behavior belongs. The preview’s visual classes are website styles; use your own design system.
  2. Connect the behavior. Copy the JavaScript tab and call its exported mount(element) after your component’s elements exist. Replace simulated delays and data operations with your own application code.
  3. Clean up. Call the returned cleanup when the component unmounts. It aborts the example’s listeners and releases the helper’s timers, observers or state.

API and lifecycle

Call focusInvalid(form) after a failed submission. It finds the first matching invalid field that is visible, enabled and outside inert content, focuses it and returns that element, or null.

Interface
form, optional selector
Lifecycle
This is a one-off operation with no persistent listeners. For custom widgets, pass a selector matching the widget's focusable trigger rather than its hidden backing input.

Accessibility and safety

Implementation notes

Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.

Moving focus is only part of error recovery. Keep a visible error message associated with the field, preserve values and validate on the server.

What to check

Submit multiple invalid fields and confirm the first visible field receives focus. Hidden, disabled and inert controls should be skipped.