liveBook · Manning

Form-associated callback

As explained in Web Component Development with Modern Libraries and Tooling

A form-associated custom-element lifecycle callback invoked when the element is associated with a form.

A form-associated callback is a lifecycle method on a custom element. The browser calls `formAssociatedCallback()` when the element is added to the DOM inside a form and its class sets `static formAssociated = true`. A practical use is saving the element’s initial value for a later form reset. section 3.2

Listing 3.14 radio-group example
<form action="https://httpbin.org/post" method="post"> #1
  <radio-group
    legend="Primary Color"
    labels="Red,Green,Blue"
    name="primaryColor"
    value="red"
    values="red,green,blue"
  >
    <div slot="before">Choose a primary color.</div> #2
    <div slot="after">This will be the most used color.</div> #3
  </radio-group>
  <div>
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>
  </div>
</form>

The radio-group element sits inside a form with Submit and Reset buttons; its `value` attribute supplies the initial selection. section 3.10

Save and restore the selection

In the radio-group class, `formAssociatedCallback() { this.#initialValue = this.value; }` saves the starting selection. When the form is reset, `formResetCallback() { this.value = this.#initialValue; }` restores it. Assigning `value` also updates the selected radio button and the value used for form submission. section 3.10

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Defines when the callback runs and shows a short implementation that saves a value; does not explore callback arguments or browser internals.
Examples
Demonstrates a radio-group element inside a submit/reset form, with callbacks that save and restore its selection.
What it assumes
Introduces lifecycle callbacks for `HTMLElement` subclasses while using JavaScript classes, attributes, and HTML forms in the example.
What you can do after
Build it from scratch: save a radio group’s starting value in `formAssociatedCallback()` and restore it in `formResetCallback()`.
How it connects
Links custom-element lifecycle callbacks, HTML forms, value setters, and form reset.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.