Form lifecycle callbacks
Learn the form-associated custom element lifecycle callbacks: formResetCallback, formDisabledCallback with a fieldset, and formStateRestoreCallback after Back.
- 01Say when each one runsName what makes the browser call each of the four callbacks, what it passes, and the order Chrome uses.
- 02Put things backMake a reset restore the default value, the form value, and the validity, and make a restore show the state again.
- 03Follow the disabled stateTurn your own controls off from
formDisabledCallback(), never the host's attribute, and makereadonlyblock edits.
What are form lifecycle callbacks?
It's Saturday at Leaf and Kettle, and Asha is ordering online. Sencha, three cups, and a note for the kitchen. Then she changes her mind and presses Clear order. The note goes back to how it started. Ravi's tea-cups doesn't. It still says 3.
Meena has added a gift section too. It stays switched off until you tick This is a gift. Everything in it turns grey, except tea-cups. Its + button still works. And when Asha leaves the page and presses Back, her note is there again. Her cups aren't. How does a custom element hear what its form is doing?
Form lifecycle callbacks are four methods a form-associated custom element can have. The browser calls each one by name when something happens to the element's form:
formAssociatedCallback(form)when it joins a form or leaves one;formResetCallback()when its form is reset;formDisabledCallback(disabled)when it's switched off or on;formStateRestoreCallback(state, reason)when the browser gives back what the person typed, as after Back.
Here is a stand-in tea-cups with all four. Each one only prints what it gets. The class is in the tea-cups.js tab:
<form id="order"> <fieldset id="gift"> <legend>Gift</legend> <tea-cups name="cups">2 cups</tea-cups> </fieldset> <button type="reset">Clear order</button> <button type="button" id="switch">Switch the gift section</button></form><script src="tea-cups.js"></script><script> document.querySelector("#switch").addEventListener("click", () => { const gift = document.querySelector("#gift"); gift.disabled = !gift.disabled; });</script>class TeaCups extends HTMLElement {
static formAssociated = true;
formAssociatedCallback(form) {
console.log("formAssociatedCallback:", form?.id ?? null);
}
formResetCallback() {
console.log("formResetCallback");
}
formDisabledCallback(disabled) {
console.log("formDisabledCallback:", disabled);
}
formStateRestoreCallback(state, reason) {
console.log("formStateRestoreCallback:", state, reason);
}
}
customElements.define("tea-cups", TeaCups);- On the page, lines 2 to 5 put tea-cups in a fieldset called gift, inside the form.
- Line 6 is a reset button. Lines 11 to 14 switch the fieldset off and on.
- In the tab, line 2 makes the class form-associated, as in lesson 16.1. The callbacks need nothing else.
- Lines 4, 8, 12, and 16 are the four callbacks. Each one prints its name and what it got.
- When the page opens, it prints
formAssociatedCallback: order. tea-cups found its form. - Press Clear order:
formResetCallback. - Press Switch the gift section:
formDisabledCallback: true. Press it again:formDisabledCallback: false.
The fourth needs a real Back button. The restore section shows it.
Meena runs the shop with a few announcements. Ravi, you're on the front counter now. Closing time, set the tables. The garden is closed. Asha is back for her order. Ravi keeps a card for each one, with what to do. When an announcement has no card, he carries on as before.
- In real life: Meena's announcement
- In JavaScript: The browser calling a callback by name
- In real life: Ravi's card for that announcement
- In JavaScript: The method you write, like
formResetCallback() - In real life: An announcement with no card
- In JavaScript: A callback your class doesn't have: nothing runs
- In real life: Ravi doing what the card says
- In JavaScript: Your code putting the element right
The browser tells your element what its form did. Your class decides what that means. A reset, a closed fieldset, or the Back button changes nothing inside your element until one of these methods does it.
Why it matters: the browser can't reach into your shadow root. These four calls are how it lets you know.
The HTML Standard lists all four with the other custom element reactions. They belong to form-associated custom elements, which work in Chrome 77, Firefox 98, and Safari 16.4 and later. They're Baseline widely available on web-features.
When is formAssociatedCallback called?
Every form control has a form owner: the form it belongs to, as lesson 16.1 showed. When the owner changes, formAssociatedCallback(form) runs. It gets the new form, or null when there's none.
The HTML Standard works out the owner again at certain moments. It calls the callback only if the answer changed. Try six changes. Only line 7 changes:
<form id="order"><tea-cups name="cups">2 cups</tea-cups></form><form id="gift"></form><script src="tea-cups.js"></script><script> const cups = document.querySelector("tea-cups"); console.log("Now line 7 runs."); cups.remove();</script>disconnectedCallback runs, then formAssociatedCallback gets null. Off the page, tea-cups has no form.
class TeaCups extends HTMLElement {
static formAssociated = true;
connectedCallback() {
console.log("connectedCallback");
}
disconnectedCallback() {
console.log("disconnectedCallback");
}
formAssociatedCallback(form) {
console.log("formAssociatedCallback:", form?.id ?? null);
}
}
customElements.define("tea-cups", TeaCups);- In the tab, lines 4, 8, and 12 print three callbacks.
- On the page, line 1 is tea-cups in the order form. Line 2 is an empty gift form.
- Line 3 defines the tag, so tea-cups upgrades. That prints
connectedCallbackandformAssociatedCallback: orderbefore line 7 runs.
- Remove it:
disconnectedCallback, thenformAssociatedCallback: null. - Move it to #gift: disconnected,
null, connected, thenformAssociatedCallback: gift. - Move it in #order: the same four lines, ending with
order. form="gift": onlyformAssociatedCallback: gift.form="no-such-form":formAssociatedCallback: null. No form has that id.- A new name: nothing more.
So a move is a leave and then a join, even inside the same form. And a new form attribute runs the callback without any connect. Removing the whole form, with tea-cups inside, runs only disconnectedCallback. tea-cups still belongs to that form. Both are just off the page.
Leaf and Kettle has two shops. Every staff badge names a branch. When Ravi moves to the Station Road shop, the manager takes his badge and gives him a new one. Even when he moves desks in the same shop, the badge comes off and goes back on. A badge with no branch means he isn't working anywhere.
- In real life: The branch on the badge
- In JavaScript: The form passed to
formAssociatedCallback(form) - In real life: A badge with no branch
- In JavaScript:
null: no form owner - In real life: Badge off, badge on, even in the same shop
- In JavaScript: A move:
null, then the form again
Why it matters: if your element listens to its form, this is where to move the listener. Take it off the old form, and add it to the new one.
Which callback runs first?
The lifecycle in order put connectedCallback and the others in order. Where do the form callbacks go? That depends on how the element arrives. Here is a disabled tea-cups in a form. Move its script:
<script src="tea-cups.js"></script><form id="order"><tea-cups name="cups" disabled>2 cups</tea-cups></form>The parser builds tea-cups with its disabled attribute, then puts it on the page. So formDisabledCallback runs before connectedCallback.
class TeaCups extends HTMLElement {
static formAssociated = true;
constructor() {
super();
console.log("constructor");
}
connectedCallback() {
console.log("connectedCallback");
}
formAssociatedCallback(form) {
console.log("formAssociatedCallback:", form?.id ?? null);
}
formDisabledCallback(disabled) {
console.log("formDisabledCallback:", disabled);
}
}
customElements.define("tea-cups", TeaCups);In the tab, lines 4 to 7 print from the constructor. Lines 9, 13, and 17 print three callbacks.
- Script before the form:
constructor,formDisabledCallback: true,connectedCallback,formAssociatedCallback: order. - Script after the form:
constructor,connectedCallback,formDisabledCallback: true,formAssociatedCallback: order.
With the class defined first, the parser builds tea-cups and sets its disabled attribute. Only then does it put tea-cups on the page. So formDisabledCallback runs before connectedCallback. In an upgrade, tea-cups is on the page already, so connectedCallback comes first. The HTML Standard's upgrade steps queue formAssociatedCallback before formDisabledCallback. Here, Chrome runs formDisabledCallback first.
Why it matters: a form callback can run before connectedCallback. Build your shadow root in the constructor, as What the constructor may do recommends. Then every callback can use it.
What does formResetCallback do?
A form is reset by a reset button, or by form.reset() in script. Inputs then go back to their defaults. The HTML Standard's steps do two things, in this order:
- Fire a
resetevent at the form. It bubbles, and a listener can cancel it. - If nobody cancelled it, reset every control the form owns. For a form-associated element, that means calling
formResetCallback().
Try both. Type in the note, then press Clear order. Then tick Keep my order, type again, and press it once more:
<form id="order"> <input name="note" aria-label="Note" value="No sugar"> <tea-cups name="cups">2 cups</tea-cups> <button type="reset">Clear order</button></form><label><input type="checkbox" id="keep"> Keep my order</label><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("reset", (event) => { console.log("reset event. The note says:", form.elements.note.value); if (document.querySelector("#keep").checked) event.preventDefault(); });</script>- Line 2 is a note with a default, No sugar. Line 3 is tea-cups, with the overview's tea-cups.js.
- Lines 10 to 13 listen for
reset. Line 11 prints the note. Line 12 cancels the reset while Keep my order is ticked.
- The first time:
reset event. The note says: Two sugars, thenformResetCallback. The note says No sugar again. - With Keep my order: only
reset event. The note says: Lots of milk. Nothing resets.
Look at line 11 again. In the listener, the note still holds what Asha typed. The event comes first, and the controls reset after it. Chrome's reset() does it in that order:
void HTMLFormElement::reset() { // ... if (DispatchEvent(*Event::CreateCancelableBubble(event_type_names::kReset)) != DispatchEventResult::kNotCanceled) { is_in_reset_function_ = false; return; } // ... ListedElement::List elements(ListedElements()); for (ListedElement* element : elements) { if (auto* html_form_element = DynamicTo<HTMLFormControlElement>(element)) { html_form_element->Reset(); } else if (element->IsElementInternals()) { CustomElement::EnqueueFormResetCallback(element->ToHTMLElement()); } } // ...}In plain words, line by line:
- Line 1 is the form's reset().
- Lines 3 and 4 fire the
resetevent. If a listener cancelled it, lines 5 and 6 stop. - Lines 9 and 10 go through every control the form owns.
- Lines 11 and 12 reset a native control. Lines 13 and 14 queue formResetCallback() for a custom one.
So what goes in the callback? The browser only calls it. It doesn't know your number. Here is tea-cups with a rule like lesson 16.3's: more than 3 cups is too many. Press + twice, then Check. Then press Clear order and Check again. Only line 23 of the tab changes:
<form id="order"> <tea-cups name="cups"></tea-cups> <button type="reset">Clear order</button> <button type="button" id="check">Check</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); const shown = () => document.querySelector("tea-cups").shadowRoot.querySelector("output").textContent; document.querySelector("#check").addEventListener("click", () => { console.log(`Shows ${shown()}. Sends ${new FormData(form).get("cups")}. Valid: ${form.checkValidity()}.`); });</script>The browser only calls the method. It doesn't know your number, so it can't put it back. tea-cups still shows 4, sends 4, and stops the form.
- In the tea-cups.js tab, lines 14 to 20 are
#show(). Every change goes through it. Line 16 shows the number, line 17 hands the form the value, and lines 18 and 19 set the validity. - Line 23 is the body of formResetCallback().
- On the page, line 11 prints three things: what tea-cups shows, what the form would send, and whether it's valid.
Before Clear order, every choice prints Shows 4. Sends 4. Valid: false. After it:
- Nothing:
Shows 4. Sends 4. Valid: false. - Only the screen:
Shows 2. Sends 4. Valid: false. - Only the value:
Shows 4. Sends 2. Valid: false. this.#show(2):Shows 2. Sends 2. Valid: true.
A reset has three things to put back: what the person sees, what the form sends, and whether it's valid. Leave one out, and they disagree. The value counts twice, too. With one argument, setFormValue() also sets the state, as lesson 16.2 showed. That's what the Back button brings back.
reset event comes first, and a listener can cancel it. Only then does the browser call formResetCallback() on each control. In the playground, this.#show(2) puts all three back at once.At closing time, Meena calls out: Tables! Each table goes back to how it looks in the morning. Two cups, a menu, and a clean cloth. Not an empty table: the morning table. And if someone is still drinking, they can say Wait, and nothing is cleared.
- In real life: Meena calling Tables! first
- In JavaScript: The
resetevent, before any callback - In real life: Someone saying Wait!
- In JavaScript: A reset listener calling
preventDefault() - In real life: The morning table: two cups and a menu
- In JavaScript: The default value: here, 2 cups
- In real life: Cups, menu, and cloth, all of them
- In JavaScript: The screen, the value and state, and the validity
Back to the default, not to empty. A text input goes back to its value attribute, and a checkbox to its checked attribute, as web.dev's guide describes. Your element goes back to whatever its default is. Burton Smith's example keeps its first value for this. Exercise 3 reads a checked attribute.
Why it matters: send every change through one method, and let the reset call it with the default. Then nothing is left behind.
How does formDisabledCallback work with a disabled fieldset?
A control is disabled when it has its own disabled attribute. It's also disabled inside a <fieldset disabled>, unless it sits in that fieldset's first legend. The HTML Standard gives both rules. The browser then calls formDisabledCallback() with true, and later with false.
Here is Meena's gift section. It's off until you tick This is a gift. The checkbox sits in the legend, so the fieldset never turns it off. The page uses the overview's tea-cups.js:
<form id="order"> <fieldset id="gift" disabled> <legend><label><input type="checkbox" id="is-gift"> This is a gift</label></legend> <tea-cups name="tins">2 tins</tea-cups> </fieldset></form><script src="tea-cups.js"></script><script> const gift = document.querySelector("#gift"); document.querySelector("#is-gift").addEventListener("change", (event) => { gift.disabled = !event.target.checked; console.log("tea-cups matches :disabled:", document.querySelector("tea-cups").matches(":disabled")); });</script>- Line 2 is the fieldset, disabled from the start. Line 3 is its first legend, with the checkbox. Line 4 is tea-cups, for gift tins.
- Lines 10 to 13 run on every tick. Line 11 switches the fieldset, and line 12 prints whether tea-cups matches
:disabled.
- When the page opens:
formAssociatedCallback: orderandformDisabledCallback: true. The upgrade steps call it for an element that's already disabled. - Tick:
formDisabledCallback: false, thentea-cups matches :disabled: false. - Untick:
formDisabledCallback: true, thentea-cups matches :disabled: true.
The host matches :disabled with no help from you. And the callback runs only when the state really flips. Chrome checks that first, in DisabledStateMightBeChanged():
void ElementInternals::DisabledStateMightBeChanged() { bool new_disabled = IsActuallyDisabled(); if (is_disabled_ == new_disabled) return; is_disabled_ = new_disabled; CustomElement::EnqueueFormDisabledCallback(Target(), new_disabled);}In plain words, line by line:
- Line 2 works out whether the element is disabled now, from its attribute and its fieldsets.
- Lines 3 and 4 stop if that's what it was already.
- Line 5 keeps the new state. Line 6 queues formDisabledCallback() with it.
So a tea-cups with its own disabled hears nothing when its fieldset closes. It was off already.
What should the callback do? Lesson 16.1 showed that a disabled host gets no clicks, but the buttons in its shadow root still work (the attributes playground). Try three answers. Press +, then Check. Tick This is a gift, press + again, and Check. Only line 19 of the tab changes:
<form id="order"> <fieldset id="gift" disabled> <legend><label><input type="checkbox" id="is-gift"> This is a gift</label></legend> <tea-cups name="tins"></tea-cups> </fieldset> <button type="button" id="check">Check</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); const tins = document.querySelector("tea-cups"); document.querySelector("#is-gift").addEventListener("change", (event) => { document.querySelector("#gift").disabled = !event.target.checked; }); document.querySelector("#check").addEventListener("click", () => { const shown = tins.shadowRoot.querySelector("output").textContent; console.log(`Shows ${shown}. Sends ${new FormData(form).get("tins") ?? "nothing"}. Off: ${tins.matches(":disabled")}.`); });</script>The browser keeps clicks off the host. The + button in its shadow root still works, so the tins go up while the section is closed.
- In the tea-cups.js tab, lines 10 to 14 add a tin on each press of +, and hand the form the new number.
- Line 19 is the body of formDisabledCallback().
- On the page, line 17 prints what tea-cups shows, what the form would send, and whether it matches
:disabled.
- Nothing:
Shows 3. Sends nothing. Off: true., thenShows 4. Sends 4. Off: false.The + button worked while the section was closed. - Turn the button off:
Shows 2. Sends nothing. Off: true., thenShows 3. Sends 3. Off: false. - Set its own disabled:
Shows 3. Sends nothing. Off: true., thenShows 4. Sends nothing. Off: true.
formDisabledCallback(true) when the section closes. When it opens, only the top one hears false. The bottom one gave itself a disabled attribute, so it stays off.The third choice is a trap. When the section closed, the callback gave the host its own disabled attribute. When the section opened, that attribute still disabled it. Its state never flipped, so false never came. Chrome's guide to form-associated elements warns about exactly this. Material Web's form mixin sets its disabled property in this callback, and that property sets the attribute. Web Awesome adds the attribute only when the host doesn't match :disabled already.
On a rainy day, Meena ropes off the garden. Every table behind the rope is closed. When the sun comes out, she takes the rope down, and the tables open again. But one waiter hung his own Closed sign on a table when the rope went up. When the rope comes down, his table stays closed.
- In real life: The rope
- In JavaScript:
<fieldset disabled> - In real life: The tables behind it
- In JavaScript: The controls inside, which
formDisabledCallback()tells - In real life: The waiter's own Closed sign
- In JavaScript: The host's own
disabledattribute - In real life: A table that stays closed
- In JavaScript: An element stuck disabled
So switch off your own controls, and leave the host's attribute alone. Buttons and inputs take disabled. Some parts have no disabled of their own, like a div with a tabindex. Take those out of the tab order with tabIndex = -1. Say they're off with ariaDisabled = "true", and ignore their clicks.
Why it matters: a fieldset switches off a whole part of a form at once. Your element should switch off with it, and come back with it.
When is formStateRestoreCallback called?
Asha types 5 pm as her pickup time. She follows a link to the menu, then presses Back. An input still shows what she typed. For your element, the browser calls formStateRestoreCallback(state, reason).
stateis what you passed tosetFormValue()as its second argument. With one argument, it's the value, as lesson 16.2 showed.reasonis"restore".
The HTML Standard lets the browser do this after a navigation, or after it restarts. The Result can't press Back, so this page has a button that calls the method the way the browser would. The class is lesson 16.2's pickup, with a callback:
<form id="order"> <tea-pickup name="pickup"></tea-pickup> <button>Order</button></form><button id="back">Pretend the browser restored 5 pm</button><script src="tea-pickup.js"></script><script> const form = document.querySelector("#order"); document.querySelector("#back").addEventListener("click", () => { document.querySelector("tea-pickup").formStateRestoreCallback("5 pm", "restore"); }); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("pickup:", new FormData(form).get("pickup")); });</script>class TeaPickup extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML =
'<label>Pickup <input placeholder="5 pm"></label>';
this.shadowRoot.querySelector("input").addEventListener("input", (event) => this.#show(event.target.value));
}
#show(text) {
this.shadowRoot.querySelector("input").value = text;
const pm = text.match(/^([1-9]) pm$/);
const time = pm ? `${Number(pm[1]) + 12}:00` : null;
this.#internals.setFormValue(time, text);
}
formStateRestoreCallback(state, reason) {
console.log("formStateRestoreCallback:", state, reason);
this.#show(state);
}
}
customElements.define("tea-pickup", TeaPickup);- In the tab, line 9 sends every keystroke through
#show(). Line 13 puts the text in the box. Line 16 hands the form the time and the text. - Lines 19 to 22 are the callback. Line 20 prints what it got. Line 21 sends the state through
#show(), like a keystroke. - On the page, line 10 calls the callback with 5 pm and "restore".
Press Order: pickup: null. Press Pretend the browser restored 5 pm: formStateRestoreCallback: 5 pm restore, and the box says 5 pm. Press Order again: pickup: 17:00.
The course ran the same page on a real address. It typed 5 pm, followed a link, pressed Back, and pressed Order. Chrome printed:
formStateRestoreCallback: 5 pm restore
pickup: 17:00Chrome does one thing more. When the callback runs, Chrome has already put the form value back too. Without line 21, the box would be empty, and the form would still send 17:00. Blink's own comment says so, in RestoreFormControlState():
bool ElementInternals::ShouldSaveAndRestoreFormControlState() const { // We don't save/restore control state in a form with autocomplete=off. return Target().isConnected() && (!Form() || Form()->ShouldAutocomplete());}// ...void ElementInternals::RestoreFormControlState(const FormControlState& state) { ExecutionContext* execution_context = target_->GetExecutionContext(); wtf_size_t index = 0; // Per spec, the submission value shouldn't be automatically restored by the // UA, but Blink has been doing that. if (const V8ControlValue* restored_value = RestoreFromFormControlState( *execution_context, state, "Value", index)) { value_ = restored_value; } const V8ControlValue* restored_state = RestoreFromFormControlState(*execution_context, state, "State", index); if (restored_state) { CustomElement::EnqueueFormStateRestoreCallback(Target(), restored_state, "restore"); }}In plain words, line by line:
- Lines 1 to 4: Chrome saves and restores the element only while it's on the page, and not in a form with
autocomplete="off". - Lines 10 and 11 are Blink's note. The HTML Standard says the browser shouldn't put back the value itself, but Blink does.
- Lines 12 to 15 put back the old value.
- Lines 17 to 21 read the state, and queue formStateRestoreCallback() with it and "restore".
Safari's WebKit saves only the state, and hands it to the callback. It doesn't put the value back. So call setFormValue() in the callback, as line 21 does through #show(). Then every browser sends what the box shows.
At a concert, Asha hands her coat to the coat check and gets a ticket. She leaves, and comes back for the second half. The attendant hands her the coat, and she puts it on again. If she only stepped into the hall with her coat on, there's nothing to hand back.
- In real life: The coat, handed in
- In JavaScript: The state, passed to
setFormValue() - In real life: The attendant handing it back
- In JavaScript:
formStateRestoreCallback(state, "restore") - In real life: Putting the coat on again
- In JavaScript: Showing the state and calling
setFormValue() - In real life: Stepping out with the coat on
- In JavaScript: A page kept in the back/forward cache: no callback
Trying it on a real page
Chrome doesn't always restore. Three cases skip the callback, and the course's test runs each one:
- The back/forward cache. Chrome may keep the whole page while you're away. Back then shows it as it was, so there's nothing to restore.
pageshowfires withpersistedset totrue. The back/forward cache lesson covers it. Chrome can keep even pages sent with Cache-Control: no-store. - A reload. In Chrome, reloading the page starts the form fresh.
- A form with
autocomplete="off". Lines 1 to 4 above skip it.
To try it yourself, save the page and its tea-pickup.js in a folder. Serve them with lesson 1.4's dev server. Then:
- Add a second page, menu.html, and a link to it:
<a href="menu.html">Menu</a>. - Type 5 pm, follow the link, and press Back.
- Look in the Console.
formStateRestoreCallback: 5 pm restoremeans the page loaded again. If it's missing, open DevTools' Application panel and its Back/forward cache section. It says whether the cache kept the page, as web.dev's guide shows. - To make Chrome load the page again every time, start it with the --disable-back-forward-cache switch.
What about the autocomplete reason?
The HTML Standard has a second reason, "autocomplete". A browser's form filling feature may call the callback with a state it picks from what you typed before. When WebKit turned these callbacks on, its team wrote that "autocomplete" wasn't supported yet. web.dev's guide notes the same for Chrome. In Chrome's restore code above, and in WebKit's, the reason is "restore".
So treat the state like something a person typed. Send it through the same method as a keystroke, the way line 21 does, so it's checked like one.
Why it matters: Back is how most forms come back. Without the callback, your element is the one box that forgets what the person did.
What do readonly and required do on a custom element?
Lesson 16.1 said readonly takes a form-associated element out of validation. Lesson 16.3 showed that the form never checks it. That's all the browser does. The HTML Standard asks you to make the control non-editable yourself.
Here the kitchen has started Asha's order, so her pickup time is fixed. The time is also too late, so it's invalid:
<form id="order"> <tea-pickup name="pickup" readonly></tea-pickup> <button>Order</button></form><script src="tea-pickup.js"></script><script> const pickup = document.querySelector("tea-pickup"); console.log("willValidate:", pickup.willValidate); console.log("Matches :read-only:", pickup.matches(":read-only")); document.querySelector("#order").addEventListener("submit", (event) => { event.preventDefault(); console.log("pickup:", new FormData(event.target).get("pickup")); });</script>class TeaPickup extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["readonly"];
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML =
'<label>Pickup <input value="5 pm"></label>';
const box = this.shadowRoot.querySelector("input");
this.#internals.setFormValue("17:00", "5 pm");
this.#internals.setValidity({ customError: true }, "The kitchen closes at 4 pm.", box);
}
attributeChangedCallback() {
this.shadowRoot.querySelector("input").readOnly = this.hasAttribute("readonly");
}
get willValidate() {
return this.#internals.willValidate;
}
}
customElements.define("tea-pickup", TeaPickup);- In the tab, line 3 watches
readonly. Line 16 copies it onto the box, as the box's ownreadOnly. That's what stops typing. - Line 12 makes the pickup invalid, with a
customError. - On the page, line 2 gives the host readonly. Lines 8 and 9 print two checks. Line 12 prints what Order sends.
It prints willValidate: false and Matches :read-only: true. Typing in the box does nothing. Press Order: pickup: 17:00. The form sent an invalid time, because it doesn't check a readonly control. Think of a price list behind glass: you can read it, it's still the price, but you can't change it.
Now delete readonly from line 2 and run it again. It prints willValidate: true, and Order stops on the error. But it still prints Matches :read-only: true. A custom element always matches :read-only. The HTML Standard gives :read-write only to inputs, text areas, and content you can edit. So style a readonly host with :host([readonly]), not :read-only.
required means nothing to the browser either. Your class reads it and raises valueMissing, as lesson 16.3 did. And a control the form doesn't check can't stop it. So a required control that's also disabled or readonly never blocks the form, just like a native input.
Why it matters: readonly and required are promises your class keeps. The browser keeps only one small part of one of them.
Adding the four callbacks to the kit
The kit's new version, kitAfter164, gives both form controls all four callbacks. Here they are at a glance. Read each row across:
| Callback | When the browser calls it | What it gets | What the kit does |
|---|---|---|---|
formAssociatedCallback(form) | The element joins a form, leaves one, or its form attribute names another. | The new form, or null. | It hides the error, because nobody has tried to send this form yet. |
formResetCallback() | The form is reset, and no reset listener cancelled it. | Nothing. | It puts back the default value, the form value and state, and the validity. |
formDisabledCallback(disabled) | Its disabled state flips, from its own attribute or a fieldset around it. | true or false. | It turns its own buttons or fieldset off or on. |
formStateRestoreCallback(state, reason) | The page loads again after Back, and the browser gives back what it saved. | The state, and "restore". | It shows the state and calls setFormValue() again. |
Here is the order form with both, and Meena's gift section:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <tea-blend name="tea" label="Blend" required><option selected>Sencha</option><option>Jasmine</option><option>Oolong</option></tea-blend> <label for="cups">Cups</label> <tea-quantity id="cups" name="cups" max="6"></tea-quantity> <fieldset id="gift" disabled> <legend><label><input type="checkbox" id="is-gift"> This is a gift</label></legend> <label for="tins">Gift tins</label> <tea-quantity id="tins" name="tins"></tea-quantity> </fieldset> <button type="reset">Clear order</button> <button>Order</button></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); const isGift = document.querySelector("#is-gift"); const openGift = () => { document.querySelector("#gift").disabled = !isGift.checked; }; isGift.addEventListener("change", openGift); form.addEventListener("reset", () => setTimeout(openGift)); addEventListener("pageshow", openGift); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>- Line 3 is the blend, with Sencha selected. Line 5 is the cups. Lines 6 to 10 are the gift section, closed at first, with a second quantity for gift tins on line 9.
- Lines 18 to 20 open the section only while This is a gift is ticked. Line 21 runs that on every tick.
- Line 22 runs it after a reset. A reset fires no
changeevent, as the HTML Standard says.setTimeout()waits until the controls have reset, because theresetevent comes first. - Line 23 runs it on
pageshow, which fires each time the page is shown, after Back too. - Lines 24 to 27 print what the form sends.
- Press Order. It prints
tea Senchaandcups 1. The tins aren't sent: the section is off, and so are their buttons. - Tick Jasmine. Press the cups' + twice. Tick This is a gift, and press the tins' + once. Press Order:
tea Sencha,tea Jasmine,cups 3, andtins 2. - Press Clear order, then Order. It prints
tea Senchaandcups 1again.
On a real page, the course's test also left the page and pressed Back. Jasmine, 3 cups, and 2 tins came back, and the gift section was open again. That's line 23's work. Chrome puts the gift checkbox back after the page's load event, just before pageshow, and fires no change event.
Here are the quantity's four callbacks:
/** A new form, or none: the reader hasn't tried to send it yet, so no error shows. */
formAssociatedCallback() {
this.#touched = false;
this.#showError();
}
/** The form was reset: back to 1, with no error showing. */
formResetCallback() {
this.#touched = false;
this.value = 1;
}
/** Disabled by its own attribute or a <fieldset>: the buttons go off too. The host's attribute is never touched. */
formDisabledCallback(disabled) {
for (const button of this.shadowRoot.querySelectorAll("button")) button.disabled = disabled;
this.#showError();
}
/** The browser gives the number back, after Back. The value setter makes it a whole number of 1 or more. */
formStateRestoreCallback(state) {
this.value = state;
}- Lines 2 to 5: a new form starts with no error showing.
- Lines 8 to 11: a reset forgets that Asha touched it, and sets the value back to 1. The
valuesetter updates the screen, the form value and state, and the validity at once. - Lines 14 to 17 turn both buttons off or on. They never touch the host's attribute.
- Lines 20 to 22 send the state through the same setter. It turns any text into a whole number of 1 or more, so a strange state can't break it.
And here is what changed in the blend:
formStateRestoreCallback(state) {
this.#restored = state instanceof FormData ? [...state.values()] : [];
this.#build();
}
// ...
box.checked = this.#restored ? this.#restored.includes(option.value) : option.defaultSelected;
// ...
const ticked = new FormData();
for (const tea of teas) ticked.append("tea", tea);- Lines 1 to 4 keep the restored teas and build the checkboxes again. Line 6 ticks them, in place of the page's selected options.
- Lines 8 and 9: the blend now passes a state every time, the ticked teas. Even none is a state, so an empty blend comes back empty.
The blend's reset builds its checkboxes from the options again, so Sencha is ticked. Its formDisabledCallback() disables its own fieldset. The quantity also takes readonly now. Its buttons stay in the tab order with aria-disabled="true", but stop changing the number. Both hide their error while the form won't check them.
The course's test runs pages from earlier lessons with kitAfter163 and kitAfter164. Every printed line, box, form entry, and tree stays the same. The JSDoc and custom-elements.json document the new disabled and readonly attributes.
Now sort some moments by whether a form callback runs:
- Asha presses Clear order.
- Asha presses Clear order, and a reset listener calls preventDefault().
- Meena disables the fieldset around tea-cups.
- tea-cups has its own disabled attribute, and Meena disables its fieldset too.
- tea-cups sits in the fieldset's first legend, and Meena disables the fieldset.
- The page moves tea-cups into another form.
- The page gives tea-cups a new name.
- The page removes the whole form, with tea-cups inside.
- Asha presses Back, and the page loads again.
- Asha presses Back, and the page comes back from the back/forward cache.
Each card is something that happens to tea-cups or its form. Sort it: does one of the four callbacks run?
Why it matters: the kit's controls now act like the inputs beside them, through a reset, a closed section, and the Back button.
Common mix-ups
- "A reset clears my element." No. The browser only calls
formResetCallback(). Your code puts back the default, the value, and the validity. - "A reset means empty." No. Inputs go back to their default, like their
valueattribute. Yours should too. - "formResetCallback() runs on every reset." No. A
resetlistener that callspreventDefault()stops it. - "formAssociatedCallback() runs once." No. It runs whenever the form owner changes, with
nullwhen it leaves. A move runs it twice. - "Checking my own disabled attribute is enough." No. A disabled fieldset disables it too. Use
formDisabledCallback(). - "A disabled host blocks clicks inside it." No. Buttons in its shadow root still work until you turn them off.
- "Setting the host's disabled in formDisabledCallback() keeps it in step." No. It stays disabled after the fieldset opens again.
- "formStateRestoreCallback() runs every time I press Back." No. A page from the back/forward cache comes back whole. A reload and
autocomplete="off"skip it too. - "The browser puts back my form value." No, not everywhere. Chrome does, but the HTML Standard says it shouldn't, and WebKit doesn't. Call
setFormValue()in the callback. - "readonly stops edits." No. It only takes the element out of validation. Stopping edits is your code's job.
- "readonly makes the host match :read-only." No. A custom element always matches
:read-only. Style:host([readonly])instead.
Practice exercises
The page first prints formAssociatedCallback: order. Predict what it prints after that, then run it.
<form id="order"><tea-cups name="cups">2 cups</tea-cups></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("reset", (event) => event.preventDefault()); form.reset(); console.log("Done");</script><form id="order"><tea-cups name="cups">2 cups</tea-cups></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("reset", (event) => event.preventDefault()); form.reset(); console.log("Done");</script>It prints Done. Line 5 cancels the reset event, so line 6's reset() stops before it reaches any control. formResetCallback() never runs.
tea-cups sits in the first legend of a disabled fieldset. Predict what line 8 prints, then run it.
<form id="order"> <fieldset disabled> <legend><tea-cups name="cups">2 cups</tea-cups></legend> </fieldset></form><script src="tea-cups.js"></script><script> console.log("Off:", document.querySelector("tea-cups").matches(":disabled"));</script><form id="order"> <fieldset disabled> <legend><tea-cups name="cups">2 cups</tea-cups></legend> </fieldset></form><script src="tea-cups.js"></script><script> console.log("Off:", document.querySelector("tea-cups").matches(":disabled"));</script>It prints Off: false. A disabled fieldset doesn't disable what's in its first legend. tea-cups was never off, so formDisabledCallback() never ran.
tea-milk starts ticked because of its checked attribute. Untick Add milk, press Clear order, then Order: it prints milk: none. Fix the tea-milk.js tab so Clear order brings the milk back. What does Order print then?
<form id="order"> <tea-milk name="milk" checked></tea-milk> <button type="reset">Clear order</button> <button>Order</button></form><script src="tea-milk.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("milk:", new FormData(form).get("milk") ?? "none"); });</script><form id="order"> <tea-milk name="milk" checked></tea-milk> <button type="reset">Clear order</button> <button>Order</button></form><script src="tea-milk.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("milk:", new FormData(form).get("milk") ?? "none"); });</script>The tea-milk.js tab adds formResetCallback(). It ticks the box again from the checked attribute, the default, and calls #send(), so the form value and the state follow. Order prints milk: on.
The gift section is off. Press + anyway, then Check: the tins go up to 3. The class watches only its own disabled attribute. Fix the tea-cups.js tab. What does Check print then?
<form id="order"> <fieldset id="gift" disabled> <legend><label><input type="checkbox" id="is-gift"> This is a gift</label></legend> <tea-cups name="tins"></tea-cups> </fieldset> <button type="button" id="check">Check</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); const tins = document.querySelector("tea-cups"); document.querySelector("#is-gift").addEventListener("change", (event) => { document.querySelector("#gift").disabled = !event.target.checked; }); document.querySelector("#check").addEventListener("click", () => { const shown = tins.shadowRoot.querySelector("output").textContent; console.log(`Shows ${shown}. Sends ${new FormData(form).get("tins") ?? "nothing"}. Off: ${tins.matches(":disabled")}.`); });</script><form id="order"> <fieldset id="gift" disabled> <legend><label><input type="checkbox" id="is-gift"> This is a gift</label></legend> <tea-cups name="tins"></tea-cups> </fieldset> <button type="button" id="check">Check</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); const tins = document.querySelector("tea-cups"); document.querySelector("#is-gift").addEventListener("change", (event) => { document.querySelector("#gift").disabled = !event.target.checked; }); document.querySelector("#check").addEventListener("click", () => { const shown = tins.shadowRoot.querySelector("output").textContent; console.log(`Shows ${shown}. Sends ${new FormData(form).get("tins") ?? "nothing"}. Off: ${tins.matches(":disabled")}.`); });</script>The tea-cups.js tab now turns its button off in formDisabledCallback(), which hears the fieldset too. + can't be pressed while the section is off, so Check prints Shows 2. Sends nothing. Off: true.
The button plays the Back button's part. Line 10 calls formStateRestoreCallback() with 3, if tea-cups has one: ?. skips the call when it doesn't. Press it, then Order: it prints cups: 2. Write the callback in the tea-cups.js tab. What does Order print then?
<form id="order"> <tea-cups name="cups"></tea-cups> <button>Order</button></form><button id="back">Pretend the browser restored 3</button><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); document.querySelector("#back").addEventListener("click", () => { document.querySelector("tea-cups").formStateRestoreCallback?.("3", "restore"); }); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("cups:", new FormData(form).get("cups")); });</script><form id="order"> <tea-cups name="cups"></tea-cups> <button>Order</button></form><button id="back">Pretend the browser restored 3</button><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); document.querySelector("#back").addEventListener("click", () => { document.querySelector("tea-cups").formStateRestoreCallback?.("3", "restore"); }); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("cups:", new FormData(form).get("cups")); });</script>The tea-cups.js tab adds formStateRestoreCallback(state), which sends Number(state) through #show(). The screen, the form value, and the validity change together. Order prints cups: 3.
tea-cups has readonly, but + still adds a cup. Press +, then Order: it prints cups: 3. Make + do nothing while tea-cups is readonly. What does Order print then?
<form id="order"> <tea-cups name="cups" readonly></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("cups:", new FormData(form).get("cups")); });</script><form id="order"> <tea-cups name="cups" readonly></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("cups:", new FormData(form).get("cups")); });</script>The tea-cups.js tab checks the readonly attribute in the click listener and returns early. The number stays 2, and the form still sends it, so Order prints cups: 2.
Check your understanding
Question 1 of 7A tag joins a form, the form resets, and the tag leaves. What does this page print?
Read the code, then predict<form id="order"></form> <script> customElements.define("tea-cups", class extends HTMLElement { static formAssociated = true; formAssociatedCallback(form) { console.log("form:", form?.id ?? null); } formResetCallback() { console.log("reset"); } }); const form = document.querySelector("#order"); form.append(document.createElement("tea-cups")); form.reset(); form.querySelector("tea-cups").remove(); </script>Choose an answer to see the explanation.
Question 2 of 7A reset listener calls event.preventDefault(). What happens to tea-cups?
Choose an answer to see the explanation.
Question 3 of 7tea-cups has its own disabled attribute and sits in a disabled fieldset. The page enables the fieldset. What happens?
Choose an answer to see the explanation.
Question 4 of 7Why shouldn't formDisabledCallback() set the host's own disabled attribute?
Choose an answer to see the explanation.
Question 5 of 7tea-cups called setFormValue("3"), with one argument. What state does formStateRestoreCallback() get?
Choose an answer to see the explanation.
Question 6 of 7Asha presses Back, and Chrome shows the page from its back/forward cache. Does formStateRestoreCallback() run?
Choose an answer to see the explanation.
Question 7 of 7What does readonly do for a form-associated custom element, on its own?
Choose an answer to see the explanation.
Key takeaways
- The browser calls four methods by name:
formAssociatedCallback(form),formResetCallback(),formDisabledCallback(disabled), andformStateRestoreCallback(state, reason). - formAssociatedCallback runs whenever the form owner changes, with
nullwhen there's none. A move runs it twice. - A form callback can run before connectedCallback, so build your shadow root in the constructor.
- A reset fires the
resetevent first. If a listener cancels it, no callback runs. - In formResetCallback, put back the default: what's shown, the form value and state, and the validity.
- formDisabledCallback runs when the state flips, from the element's own attribute or a fieldset outside its first legend. Turn your own controls off, never the host's attribute.
- formStateRestoreCallback runs when the page loads again after Back. Show the state and call
setFormValue(). The back/forward cache, a reload, andautocomplete="off"skip it. readonlyonly takes the element out of validation, so block edits yourself.requiredmeans what your class makes it mean.
Remember the one-liner.
The browser tells your element what its form did. Your class puts back the value, the state, and its own controls.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- Custom element reactions, HTML Standard.
- Upgrading an element: the form callbacks it queues, HTML Standard.
- Reset the form owner, HTML Standard.
- Resetting a form, HTML Standard.
- HTMLFormElement::reset(), html_form_element.cc at 158.0.8127.18, Chromium.
- More capable form controls, Lifecycle callbacks, Arthur Evans, web.dev.
- Disabled form controls, HTML Standard.
- ElementInternals::DisabledStateMightBeChanged(), element_internals.cc at 158.0.8127.18, Chromium.
- Form-associated custom elements, Modern Web Guidance, Chrome for Developers.
- form-associated.ts at 875a8b6b, formDisabledCallback(), Material Web.
- webawesome-form-associated-element.ts at 584c378a, the disabled attribute and the callbacks, Web Awesome.
- State of a form-associated custom element, HTML Standard.
- ElementInternals: save and restore, element_internals.cc at 158.0.8127.18, Chromium.
- FormAssociatedCustomElement.cpp at WebKit-7625.2.8, save and restore, WebKit.
- Back/forward cache, Philip Walton and Barry Pollard, web.dev.
- Enabling bfcache for Cache-Control: no-store, Chrome for Developers.
- content_switches.cc at 158.0.8127.18, --disable-back-forward-cache, Chromium.
- ElementInternals and Form-Associated Custom Elements, Form-Associated Custom Element Callbacks, Ryosuke Niwa, WebKit blog.
- More capable form controls, Restore form state, Arthur Evans, web.dev.
- Form-associated custom elements and the readonly attribute, HTML Standard.
- The :read-only and :read-write pseudo-classes, HTML Standard.
- Custom Forms with Web Components and "ElementInternals", ElementInternals Lifecycle Hooks, Burton Smith, DEV.
- Form-associated custom elements, web-features, on Web Platform Status.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Wrap a native input or build your own. It compares an input wrapped in a shadow root with a control built from scratch.