Joining a form
Learn form-associated custom elements: set static formAssociated, call attachInternals(), and make a web component send its value with its form.
- 01Explain the missing valueShow with
FormDatawhy an input inside a shadow root never reaches the page's form. - 02Make an element join its formUse
static formAssociated = true,attachInternals(), aname, andsetFormValue(), and readformandlabels. - 03Pick the form and the designSay which form owns an element, and choose between a host that is the control and a host that wraps one.
What are form-associated custom elements?
Leaf and Kettle takes orders online now. The order form has a box for the tea. Ravi adds his own tag for the number of cups, <tea-cups>. Inside its shadow root sits a number box. It looks right. Asha orders two cups of Sencha.
In the kitchen, her order arrives. It says Sencha. It doesn't say how many cups. The box was right there in the form. Why wasn't it sent?
A form only collects controls from its own tree, so an input inside a shadow root is never sent. A form-associated custom element fixes that. Its class says static formAssociated = true, and calls attachInternals(). Then the host itself is the form control, and it gives the form a value with setFormValue().
Here is Ravi's form. The class is in the tea-cups.js tab:
<form id="order"> <input name="tea" value="Sencha"> <tea-cups></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>customElements.define("tea-cups", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML =
'<label>Cups <input name="cups" type="number" value="2"></label>';
}
});- On the page, line 2 is a text box named
tea. Line 3 is Ravi's tag. - In the
tea-cups.jstab, line 4 attaches a shadow root. Line 5 puts the number box in it, namedcups, with the value 2. - Back on the page, line 10 stops the form from loading a new page. Line 11 builds a
FormData: the list of names and values the form would send. Then it prints each one.
Press Order. It prints tea Sencha, and nothing more. The cups are missing, as in Asha's order. If FormData is new to you, the JavaScript lesson FormData covers it.
Now the fix. The page gives the name to the host, and the class joins the form:
class TeaCups extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML =
'<label>Cups <input type="number" value="2"></label>';
const box = this.shadowRoot.querySelector("input");
this.#internals.setFormValue(box.value);
box.addEventListener("input", () => this.#internals.setFormValue(box.value));
}
}
customElements.define("tea-cups", TeaCups);<form id="order"> <input name="tea" value="Sencha"> <tea-cups name="cups"></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>- In the tab, line 2 makes the class form-associated: the browser treats its elements as form controls.
- Line 3 asks for the element's internals, a private object for the class alone. You met it in lesson 13.2, for ARIA.
- Line 8 keeps the box, but without a name. Line 10 hands its value to the form. Line 11 does it again each time the value changes.
- On the page, line 3 now reads
<tea-cups name="cups">. The name moved to the host.
Press Order. It prints tea Sencha and cups 2. Type 3 in the box, and press Order again. Now it says cups 3.
cups 2.At closing time, Meena writes the stock list. She walks the shelves and writes down every jar she can see. One shelf holds a sealed tin. She can't open it, so its leaves never make the list. Then Ravi writes the amount on the lid. Meena reads the lid, and the tin is on the list.
- In real life: Meena's stock list
- In HTML:
new FormData(form) - In real life: The jars on the open shelves
- In HTML: Inputs in the page, like
<input name="tea"> - In real life: The sealed tin
- In HTML: The shadow root of
<tea-cups> - In real life: The amount written on the lid
- In HTML: The host's
name, and the value fromsetFormValue()
A form can't reach into a shadow root, so the host must be the control. Give its class static formAssociated = true. Call attachInternals(). Give the host a name, and hand the form its value with setFormValue().
Why it matters: a value that is never sent is a lost order. And nothing warns you. The form looks complete.
Form-associated custom elements work in Chrome 77, Firefox 98, and Safari 16.4 and later. web-features lists them as Baseline widely available, so every current browser has them.
Why isn't an input in shadow DOM sent with its form?
Every control has a form owner: the one form it belongs to. A form sends only the controls it owns. form.elements lists them. The HTML Standard says how a control finds its owner. By default, it's the nearest <form> among its parents.
Now recall lesson 6.1. A shadow root is a separate tree. Its children have parents up to the shadow root, and no further. The host isn't their parent. So the climb to find a form stops at the root. Try it with the same box, in two places:
<form id="order"> <input name="tea" value="Sencha"> <input name="cups" type="number" value="2"></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); console.log("Controls:", form.elements.length); for (const [name, value] of new FormData(form)) console.log(name, value);</script>The box is a child of the form, so the form is its form owner. form.elements counts it, and FormData has its value.
- Line 3 is the box itself, or the tag with the box in its shadow root.
- Line 8 prints how many controls the form owns. Line 9 prints what it would send.
- In the page:
Controls: 2,tea Sencha, andcups 2. - In a shadow root:
Controls: 1andtea Sencha. The box isn't even on the list.
What about the form attribute? It lets a control name its form by id, even from outside the form. Ravi tries it on the box inside the shadow root:
<form id="order"> <input name="tea" value="Sencha"> <tea-cups></tea-cups></form><script src="tea-cups.js"></script><script> const box = document.querySelector("tea-cups").shadowRoot.querySelector("input"); console.log("The box's form:", box.form); console.log("Its tree ends at:", box.getRootNode().constructor.name);</script>- In the
tea-cups.jstab, line 5 now ends withform="order". - On the page, line 7 finds the box. Line 8 prints its
form. Line 9 prints the kind of node its tree ends at.
It prints The box's form: null and Its tree ends at: ShadowRoot. The id lookup searches only the box's own tree, the shadow root. There is no order form in there.
customElements.define("tea-cups", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML =
'<label>Cups <input name="cups" type="number" value="2" form="order"></label>';
}
});Chrome's own code shows both rules. Here is ResetFormOwner(), the function that picks a control's form. You don't need to know C++ to follow it. Each line is explained below the box.
void ListedElement::ResetFormOwner() { HTMLElement& element = ToHTMLElement(); const AtomicString& form_id(element.FastGetAttribute(html_names::kFormAttr)); HTMLFormElement* nearest_form = element.FindFormAncestor(); // ... HTMLFormElement* new_form = nullptr; if (!form_id.IsNull() && element.isConnected()) { Element* new_form_candidate = element.GetTreeScope().getElementById(form_id); new_form = DynamicTo<HTMLFormElement>(new_form_candidate); // ... } else { new_form = nearest_form; } SetForm(new_form);}In plain words, line by line:
- Line 3 reads the control's
formattribute, if it has one. - Line 4 finds the nearest form among its parents. FindFormAncestor() walks up parent by parent, and a shadow root has no parent.
- Lines 7 to 10 run when there is a
formattribute. Line 9 looks up the id withGetTreeScope(): the control's own tree. Line 10 keeps it only if it's a form. - Line 13 runs when there is no
formattribute. It takes the nearest form from line 4. - Line 15 stores the result as the control's form owner.
Both searches stay in one tree. So a control inside a shadow root can only join a form inside that same shadow root. The page's form can never own it. The HTML Standard's steps say the same.
Before form association, people worked around this. They kept a hidden <input> in the light DOM and copied the value into it, as web.dev's guide describes. You don't need that now.
Why it matters: no setting moves a shadow input into the page's form. The host has to join instead.
What does static formAssociated do?
static formAssociated = true is a flag on the class. define() reads it once, when it registers the tag, and keeps it in the tag's definition. Every element of that tag is then a form-associated custom element. The flag has to be there before define() runs:
<form id="order"> <tea-cups name="cups"></tea-cups> <tea-sugar name="sugar"></tea-sugar></form><script> class TeaCups extends HTMLElement { static formAssociated = true; } class TeaSugar extends HTMLElement {} customElements.define("tea-cups", TeaCups); customElements.define("tea-sugar", TeaSugar); TeaSugar.formAssociated = true; const form = document.querySelector("#order"); console.log("Controls:", [...form.elements].map((control) => control.localName).join(", ")); console.log("Entries:", [...new FormData(form)].length);</script>- Lines 2 and 3 are two tags in a form.
- Lines 6 to 8 give
TeaCupsthe flag, as a static field. Line 9 makesTeaSugarwithout it. - Lines 10 and 11 define both. Line 12 adds the flag to TeaSugar, after its definition.
- Line 14 prints the tag of every control the form owns. Line 15 prints how many entries it would send.
It prints Controls: tea-cups and Entries: 0. TeaSugar's late flag did nothing. And tea-cups is a control, but sends nothing. Its value starts as null, which the next section explains.
The Saturday market keeps a list of stalls. Each stall signs up before the market opens. A stall on the list gets a spot, and a line on the takings sheet. A tea van that parks nearby isn't on the list. Painting STALL on the van later doesn't add it either.
- In real life: Signing up before the market opens
- In JavaScript:
static formAssociated = true, read bydefine() - In real life: The organizer's list of stalls
- In JavaScript:
form.elements - In real life: The takings sheet at the end of the day
- In JavaScript: The form's entries, in
FormData - In real life: Painting STALL on a van later
- In JavaScript: Setting
formAssociatedafterdefine()
The flag puts the element in four groups that the HTML Standard lists for forms:
- Listed: it shows up in
form.elements. - Submittable: the form sends its value.
- Resettable: a form reset reaches it. Lesson 16.4 handles that.
- Labelable: a
<label>can point at it.
It also gives four attributes their meaning. The table below sums up what the browser does with each. Read it row by row:
| Attribute | What the browser does with it |
|---|---|
name | It names the entry the form sends, and finds the element in form.elements. With no name, or an empty one, nothing is sent. |
disabled | It leaves the element out of the form's entries and out of validation. The host matches :disabled and gets no click events. Controls inside its shadow root still work. |
form | It gives the element to the form with that id in the same tree, instead of the form around it. |
readonly | It takes the element out of validation. That is all the browser does. Stopping changes is your code's job. |
The next examples share one small tea-cups.js. It's a stand-in, with no box. Its value is always 2, so the examples stay short:
class TeaCups extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.setFormValue("2");
}
get form() {
return this.#internals.form;
}
get labels() {
return this.#internals.labels;
}
}
customElements.define("tea-cups", TeaCups);- Lines 2 and 3 are the flag and the internals, as before.
- Line 7 gives the form the value 2, as soon as the element is built.
- Lines 10 to 16 share two things from the internals:
formandlabels. More on those soon.
Now try three of the attributes on it:
<form id="order"> <input name="tea" value="Sencha"> <tea-cups name="cups">2 cups</tea-cups></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); const cups = document.querySelector("tea-cups"); for (const [name, value] of new FormData(form)) console.log(name, value); console.log("Disabled:", cups.matches(":disabled"));</script>The host has a name and a value, so the form sends cups 2, right after the tea. It isn't disabled.
- Line 9 prints each entry the form would send.
- Line 10 asks if the host matches
:disabled.
name="cups":cups 2is sent.- No name: nothing is sent for the cups.
disabled: nothing is sent, and it printsDisabled: true.readonly:cups 2is still sent.
disabled does a little more than the playground shows. The HTML Standard keeps click events off a disabled control. So the host gets no clicks. But the controls inside its shadow root still work. Lesson 16.4 turns those off, too.
Notice what the flag doesn't add: properties. An <input> has form and name properties. Your element doesn't, until your class adds them. The HTML Standard's own example adds getters for both.
Why it matters: one line turns a tag into a form control. But the flag must be in the class from the start.
What does attachInternals() give a form control?
Lesson 13.2 covered the rules of attachInternals(). It works once per element. It works only on autonomous custom elements, not on a customized built-in. And a class can turn it off with static disabledFeatures = ["internals"]. Each case throws a NotSupportedError, as MDN and the standard's steps list. Safari ignores disabledFeatures, so there the call still works.
So what's new for forms? attachInternals() itself doesn't need the flag. But the form part of the internals does. Switch the flag in line 2 of the tab:
<form id="order"> <tea-cups name="cups"></tea-cups></form><script src="tea-cups.js"></script>attachInternals() works on any autonomous custom element, so role works. form, labels, and validity throw a NotSupportedError, because the element isn't form-associated.
- In the
tea-cups.jstab, line 2 sets the flag. Line 3 gets the internals. - Line 6 loops over four members. Line 8 reads each one. Line 9 or line 11 prints what happened.
- Without the flag:
role works, thenform,labels, andvalidityeach printNotSupportedError. - With the flag: all four print works.
Chrome's message says why: "The target element is not a form-associated custom element." Here is the whole map of what internals give a form control, as MDN lists it. Read each row across:
| What the internals hold | What it's for | Where the course teaches it |
|---|---|---|
form and labels | The element's form, and the labels that point at it. | This lesson. |
setFormValue() | The value the form sends, and a state the browser can restore. | This lesson starts it. Lesson 16.2 goes further. |
setValidity(), validity, validationMessage, willValidate, checkValidity(), and reportValidity() | Errors, like an input's, and the browser's error bubble. | Lesson 16.3. |
role and the ARIA properties | A default role and states for screen readers. | Lesson 13.2. |
states | Custom states that CSS reads with :state(). | Lesson 12.3. |
shadowRoot | The element's own shadow root, even a closed one. | Lesson 6.2. |
You have met the last three rows in lessons 13.2, 12.3, and 6.2.
This lesson needs just one method: setFormValue(). You pass it a string, and the form sends it under the host's name. You pass null, and the form sends nothing. null is also where every element starts, as the standard says. That's why tea-sugar sent nothing.
In the kitchen, each station pins a note to the order board. When the order goes out, Ravi reads every note. If a station changes its mind, it pins a new note over the old one. A station with no note adds nothing.
- In real life: Pinning a note: Sencha, 2 cups
- In JavaScript: internals.setFormValue("2")
- In real life: Pinning a new note over the old one
- In JavaScript: Calling
setFormValue()again when the value changes - In real life: A station with no note
- In JavaScript:
setFormValue(null), or never calling it - In real life: Ravi reading the board as the order goes out
- In JavaScript:
new FormData(form)on submit
That's why the overview's tea-cups.js calls setFormValue() twice. Line 10 pins the first note. Line 11 pins a new one on every change. Lesson 16.2 covers the rest: files, many values at once, and the state the browser restores.
Why it matters: the form sends only what you last gave it. A value you never pass is never sent.
How does a custom element find its form?
A form-associated element finds its form owner the same way an <input> does. There are two rules:
- If it has a
formattribute, its owner is the form with that id, in its own tree. If there is no such form, it has no owner at all. - Otherwise, its owner is the nearest
<form>among its parents.
The browser works this out again whenever it could change. That's when the element joins or leaves the page, when it moves, when its form attribute changes, and when its tag is defined. The HTML Standard lists those moments. Your class reads the result as internals.form. Try three places for the stand-in:
<form id="order"> <input name="tea" value="Sencha"> <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("Form owner:", cups.form?.id ?? null); const form = document.querySelector("#order"); for (const [name, value] of new FormData(form)) console.log(name, value);</script>No form attribute, so the cups take the nearest form element they sit in: order. The order form sends them.
- Lines 1 to 4 are the order form. Line 5 is after it.
- Line 9 prints the id of the stand-in's form, from the
formgetter in its tab. - Line 11 prints what the order form would send.
- Inside the form:
Form owner: order, and the cups are sent. - After it, with
form="order":Form owner: order. The id reaches it. - Inside it, with
form="gift":Form owner: gift. The order form sends only the tea.
form="order" only looks inside that root. So it has no form.At a wedding, guests sit at the table where they stand. A seat card can send a guest to another table: Table 3. But the card only counts tables in the same hall. A guest in the side room can't be sent to Table 3 in the main hall.
- In real life: The table a guest stands at
- In JavaScript: The nearest
<form>among the element's parents - In real life: A card that says Table 3
- In JavaScript:
form="order" - In real life: Only the tables in this hall
- In JavaScript: Only ids in the element's own tree
- In real life: The side room with its own tables
- In JavaScript: A shadow root
So where can a form-associated element sit, and still join the page's form? Anywhere in the page's own tree. That includes slotted content. A tag the page puts inside another component stays in the page's tree. Only the slot shows it somewhere else. Exercise 6 uses that.
Your class can share the owner with a getter, as the stand-in does in lines 10 to 12. The HTML Standard gives form-associated elements no form property of their own. It puts form on the internals, as MDN shows.
Why it matters: the form you see around a tag isn't always its owner. Check internals.form.
How do name and labels work on a custom element?
The name attribute does two jobs, as it does on an <input>. It's the name of the entry the form sends. And form.elements finds the element by it, as Form properties & elements showed for inputs. With no name, or an empty one, the standard's steps skip the element. You saw that in the attributes playground.
Labels come from the internals too. Lesson 13.4 showed that a form-associated element is labelable. A page <label> can point at it, and Chrome and Firefox use the label as its name. Here both meet in the order form:
<form id="order"> <label for="cups">Cups</label> <tea-cups id="cups" name="cups">2 cups</tea-cups></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); const cups = form.elements.cups; console.log("By name:", cups.localName); console.log("Labels:", cups.labels.length, cups.labels[0].textContent); console.log("Its name property:", cups.name);</script>- Line 2 is a label for
cups. Line 3 is the stand-in, with that id and the namecups. - Line 8 finds the element by its name, in
form.elements. Line 9 prints its tag. - Line 10 prints how many labels point at it, and the first one's text. That's the
labelsgetter in the tab. - Line 11 reads a
nameproperty.
It prints By name: tea-cups, Labels: 1 Cups, and Its name property: undefined. The attribute works. But there is no name property until your class adds one, as the kit does later in this lesson.
Lesson 13.4 also covered the rest of labels. A click on the label focuses the control and clicks it. Safari doesn't use the label as the name, so give the element a name of its own too, as MDN suggests. And a label names the host. That only helps when the host is the control. The next section shows the other kind.
Why it matters: the name is how your server finds the value. The label is how people find the control.
Interactive and container form controls
A form-associated element can be built in one of two ways:
- Interactive: the host is the control. It has the role, takes focus, and handles keys. A switch is like this.
- Container: the host wraps a native control, like an
<input>, in its shadow root. The native control does the work.
In both, the host joins the form. It has to: nothing in its shadow root can. Here is one of each, in one order form:
<style> tea-toggle { border: 1px solid gray; border-radius: 4px; padding: 2px 6px; } tea-toggle:state(checked) { background: palegreen; }</style><form id="order"> <tea-toggle name="milk">Add milk</tea-toggle> <tea-cups name="cups"></tea-cups> <button>Order</button></form><script src="tea-toggle.js"></script><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>class TeaToggle extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.addEventListener("click", () => this.#flip());
this.addEventListener("keydown", (event) => {
if (event.key !== " ") return;
event.preventDefault();
this.#flip();
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
#flip() {
const on = this.#internals.ariaChecked !== "true";
this.#internals.ariaChecked = String(on);
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.setFormValue(on ? "on" : null);
}
}
customElements.define("tea-toggle", TeaToggle);- Line 2 makes the switch form-associated.
- Lines 7 and 8 give the host the role
switchand the state not checked, as in lesson 13.2. - Lines 9 to 14 flip it on a click, or on Space.
- Line 18 puts the host in the Tab order, with a
tabindex. - Lines 24 and 25 set the
checkedstate, which the page's CSS colors. Line 26 hands the form"on", ornullwhen it's off.
class TeaCups extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML =
'<label>Cups <input type="number" value="2"></label>';
const box = this.shadowRoot.querySelector("input");
this.#internals.setFormValue(box.value);
box.addEventListener("input", () => this.#internals.setFormValue(box.value));
}
}
customElements.define("tea-cups", TeaCups);This is the overview's tea-cups.js, with one change. Line 7 now passes delegatesFocus: true. As lesson 9.3 showed, focus on the host goes to the box inside.
Press Order. It prints cups 2: the switch is off, so it sends nothing. Click Add milk, and press Order again. Now it prints milk on and cups 2. Press Tab from the top of the result, too. The first stop is the switch's host. The second is the box inside tea-cups.
At the station, you can buy a ticket two ways. A ticket machine is the thing you use: you press its own buttons. A ticket booth has a clerk inside, and you talk to the clerk through the window. Either way, the ticket comes out with the station's name on it.
- In real life: The ticket machine
- In JavaScript: A host that is the control, like
tea-toggle - In real life: The clerk in the booth
- In JavaScript: The native
<input>inside the shadow root - In real life: Talking to the clerk through the window
- In JavaScript:
delegatesFocussending focus inside - In real life: The station's name on the ticket
- In JavaScript: The host's name and value in
FormData
Which design fits? Follow lesson 14.1's rule: the element with the role and state is the one that takes focus. In the interactive design, that's the host. In the container, it's the native control, so the host delegates focus to it. The table puts the two side by side. Read each row across:
| Question | When the host is the control | When the host wraps a control |
|---|---|---|
| Who has the role? | The host, through internals.role. | The native control inside, like an <input>. |
| Who takes focus? | The host, with tabindex="0". | The control inside. The host delegates focus to it. |
| Who handles keys? | Your code, on the host. | The native control does it for you. |
What does a page <label> name? | The host, which is the control. | The host, not the control inside. Lesson 13.4 shows the fix. |
| Who sends the value? | The host, with setFormValue(). | The host too. The control inside can't reach the form. |
The container's label row is the trap from lesson 13.4. A page label names the host, not the input inside. So here the box takes its name from a label inside its own shadow root. WebKit's Ryosuke Niwa builds a container the same way: an input in a shadow root that delegates focus. Lesson 16.5 compares the two designs in depth.
Why it matters: the design decides where the role, the focus, and the name go. The value always goes through the host.
Adding the quantity to the order form
The kit's tea-quantity has a number with - and + buttons, all in its shadow root. So until now, no form could send it. The kit's new version, kitAfter161, makes it form-associated. Here it is in the order form:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <label>Tea <select name="tea"><option>Sencha</option><option>Oolong</option></select></label> <label for="cups">Cups</label> <tea-quantity id="cups" name="cups"></tea-quantity> <button>Order</button></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>- Line 3 is a tea picker, a plain select.
- Line 4 is a label for the quantity. Line 5 is the quantity, named
cups. - Lines 11 to 14 print the entries when you press Order.
Press Order. It prints tea Sencha and cups 1. Press + twice, then Order again: now it's cups 3. Here are the lines tea-quantity.js gains:
import { attachInternals } from "./internals.js";
// ...
static formAssociated = true;
#internals = attachInternals(this);
// ... at the end of the constructor:
this.#internals.setFormValue(String(this.#value));
// ... in #change(), after it shows the new number:
this.#internals.setFormValue(String(value));
// ... and two properties, like a native control's:
get form() {
return this.#internals.form;
}
get name() {
return this.getAttribute("name");
}- Line 1 imports the kit's helper from lesson 15.3. It attaches internals and lists them where checkers like axe can read them.
- Lines 3 and 4 add the flag and the internals.
- Line 6 gives the form the first number. Line 8 gives it each new one.
String()turns the number into text. - Lines 10 to 15 add
formandnameproperties, like an input's.
The quantity is a container: its controls are native buttons. Its label still names its number, through Reference Target, as lesson 13.3 set up. In a browser without Reference Target, the label now names the host too, as in lesson 13.4. The JSDoc and custom-elements.json document the new name attribute and both properties.
Nothing else changes. The card that holds a quantity gives it no name, so the card sends nothing. The course's test runs pages from earlier lessons with both versions of the kit. Every printed line, every box, and Chrome's tree stay the same, and lesson 15.3's axe audit still passes.
Now sort some controls by what reaches the form:
<input name="cups">inside the shadow root of<tea-cups>, in the form.- A form-associated
<tea-cups name="cups">with a value, in the form. - The same element with no
name. - The same element with
disabled. - The same element with
readonly. - The same element after the form, with
form="order". <tea-cups name="cups">whose class has noformAssociated.
Sort each control by whether the order form sends it.
Why it matters: the kit's quantity now works in any form, with no hidden input and no extra code on the page.
Common mix-ups
- "An input inside a shadow root is sent with the page's form." No. Its parents stop at the shadow root, so it has no form owner.
- "form="order" on the inner input fixes it." No. The id is looked up in the input's own tree, the shadow root.
- "You need a hidden input in the light DOM." No. That was the old workaround. A form-associated element sends its own value.
- "Safari doesn't support ElementInternals." No. Safari has had it since 16.4. Every current browser has form-associated custom elements.
- "You need a polyfill or feature detection." No. They're Baseline widely available. Advice to check first comes from before Safari added them.
- "You can set formAssociated later." No.
define()reads it once. Put it in the class. - "A form-associated element gets form and name properties." No. The attributes work, but the properties are yours to add.
- "You can call attachInternals() whenever you need it." No. A second call throws, and so does a call on a customized built-in. Call it once, and keep the result.
Practice exercises
The form holds an input, the stand-in tea-cups, and a tea-note. Predict what the page prints, then run it.
<form id="order"> <input name="tea" value="Sencha"> <tea-cups name="cups">2 cups</tea-cups> <tea-note name="note">Less sugar</tea-note></form><script src="tea-cups.js"></script><script> customElements.define("tea-note", class extends HTMLElement {}); const form = document.querySelector("#order"); console.log("Controls:", form.elements.length);</script><form id="order"> <input name="tea" value="Sencha"> <tea-cups name="cups">2 cups</tea-cups> <tea-note name="note">Less sugar</tea-note></form><script src="tea-cups.js"></script><script> customElements.define("tea-note", class extends HTMLElement {}); const form = document.querySelector("#order"); console.log("Controls:", form.elements.length);</script>It prints Controls: 2: the input and tea-cups. tea-cups is form-associated, from line 2 of its tab. tea-note has a name, but no flag, so the form doesn't list it.
This page uses the overview's fixed tea-cups.js. How many lines does Order print? Predict, then press Order.
<form id="order"> <input name="tea" value="Sencha"> <tea-cups></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script><form id="order"> <input name="tea" value="Sencha"> <tea-cups></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>Order prints one line, tea Sencha. The host is form-associated and has the value 2, but line 3 gives it no name. Without a name, the form skips it.
The result shows an error, and Order prints only the tea. Fix the class in the tea-cups.js tab. What is the last line Order prints then?
<form id="order"> <input name="tea" value="Sencha"> <tea-cups name="cups"></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script><form id="order"> <input name="tea" value="Sencha"> <tea-cups name="cups"></tea-cups> <button>Order</button></form><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>The tea-cups.js tab adds static formAssociated = true; as line 2. Without it, setFormValue() throws a NotSupportedError while the element is built. With it, Order prints tea Sencha, then cups 2.
The design puts the cups in a sidebar, after the form. Make the order form send them, without moving the tag. What is the last line the page prints then?
<form id="order"> <input name="tea" value="Sencha"></form><p>Sidebar: <tea-cups name="cups">2 cups</tea-cups></p><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); for (const [name, value] of new FormData(form)) console.log(name, value);</script><form id="order"> <input name="tea" value="Sencha"></form><p>Sidebar: <tea-cups name="cups" form="order">2 cups</tea-cups></p><script src="tea-cups.js"></script><script> const form = document.querySelector("#order"); for (const [name, value] of new FormData(form)) console.log(name, value);</script>Line 4 of the page adds form="order" to the tag. The id is in the same tree, the page, so the order form owns the cups. The page prints tea Sencha, then cups 2.
The switch flips and turns green, but Order prints nothing. Make it send on while it's on, and nothing while it's off. What does Order print after one click on Add milk?
<style> tea-toggle { border: 1px solid gray; border-radius: 4px; padding: 2px 6px; } tea-toggle:state(checked) { background: palegreen; }</style><form id="order"> <tea-toggle name="milk">Add milk</tea-toggle> <button>Order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script><style> tea-toggle { border: 1px solid gray; border-radius: 4px; padding: 2px 6px; } tea-toggle:state(checked) { background: palegreen; }</style><form id="order"> <tea-toggle name="milk">Add milk</tea-toggle> <button>Order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); for (const [name, value] of new FormData(form)) console.log(name, value); });</script>The tea-toggle.js tab adds the flag as line 2, and calls setFormValue(on ? "on" : null) at the end of #flip(). After one click, Order prints milk on. A second click sets null, and the milk is no longer sent.
A row component keeps the kit's quantity in its own shadow root, with form="order". The form sends only the tea. Fix it so the form sends the cups. What is the last line the page prints then?
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <input name="tea" value="Sencha"> <tea-order-row></tea-order-row></form><script type="module"> import "./tea-kit/index.js"; customElements.define("tea-order-row", class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = '<p>Cups: <tea-quantity name="cups" form="order"></tea-quantity></p>'; } }); const form = document.querySelector("#order"); for (const [name, value] of new FormData(form)) console.log(name, value);</script><link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <input name="tea" value="Sencha"> <tea-order-row><tea-quantity name="cups"></tea-quantity></tea-order-row></form><script type="module"> import "./tea-kit/index.js"; customElements.define("tea-order-row", class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = '<p>Cups: <slot></slot></p>'; } }); const form = document.querySelector("#order"); for (const [name, value] of new FormData(form)) console.log(name, value);</script>The page puts the quantity inside tea-order-row, and the row's shadow root shows it with a slot. The quantity stays in the page's tree, inside the form, so the form owns it. The page prints tea Sencha, then cups 1.
Check your understanding
Question 1 of 7The box sits in a shadow root, with form="order". What does this page print?
Read the code, then predict<form id="order"></form> <tea-cups></tea-cups> <script> customElements.define("tea-cups", class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = '<input name="cups" value="2" form="order">'; } }); console.log(new FormData(document.querySelector("#order")).has("cups")); </script>Choose an answer to see the explanation.
Question 2 of 7A class has no formAssociated. Which members of its internals throw a NotSupportedError?
Choose an answer to see the explanation.
Question 3 of 7A page sets TeaSugar.formAssociated = true right after customElements.define(). Does tea-sugar join forms?
Choose an answer to see the explanation.
Question 4 of 7A form-associated element in a form has a value, but no name attribute. What does the form send for it?
Choose an answer to see the explanation.
Question 5 of 7What does readonly do on a form-associated element, if its class adds nothing?
Choose an answer to see the explanation.
Question 6 of 7What does cups.form give, when the tea-cups class adds no form getter of its own?
Choose an answer to see the explanation.
Question 7 of 7A form-associated component wraps an input in its shadow root. Where should focus go?
Choose an answer to see the explanation.
Key takeaways
- A form sends only the controls it owns. An input in a shadow root has no form owner, so it's never sent.
static formAssociated = truemakes the host a form control: listed, submittable, resettable, and labelable.define()reads it once.attachInternals()works without the flag, butform,labels, and the rest of the form part need it.setFormValue()gives the form its value.nullsends nothing, and every element starts there.- A control's form is the nearest
<form>among its parents, or the one itsformattribute names in its own tree. namenames the entry.disabledleaves it out.readonlyonly skips validation.- The host is the control, or it wraps one. Either way, the host sends the value, and focus goes to whatever has the role.
Remember the one-liner.
A form can't see into a shadow root, so make the host the control and hand it the value.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- Creating a form-associated custom element, HTML Standard.
- More capable form controls, Arthur Evans, web.dev.
- Association of controls and forms: the form owner, HTML Standard.
- Reset the form owner, HTML Standard.
- ListedElement::ResetFormOwner(), listed_element.cc at 158.0.8127.18, Chromium.
- HTMLElement::FindFormAncestor(), html_element.cc at 158.0.8127.18, Chromium.
- Form-associated custom element: definition and attributes, HTML Standard.
- CustomElementRegistry define() steps, HTML Standard.
- Form element categories, HTML Standard.
- Enabling and disabling form controls, HTML Standard.
- The attachInternals() method steps, HTML Standard.
- HTMLElement: attachInternals(), exceptions, MDN.
- ElementInternals: instance properties and methods, MDN.
- Form-associated custom elements: setFormValue() and the submission value, HTML Standard.
- Entry construction for a form-associated custom element, HTML Standard.
- ElementInternals: form, MDN.
- The form IDL attribute of ElementInternals, HTML Standard.
- ElementInternals: labels, accessibility concerns, MDN.
- Labelable elements, HTML Standard.
- ElementInternals and Form-Associated Custom Elements, Ryosuke Niwa, WebKit blog.
- 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: Form values. It covers everything setFormValue() can send, and the state it keeps for restoring a form.