completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Joining a form

Learn form-associated custom elements: set static formAssociated, call attachInternals(), and make a web component send its value with its form.

By the end, you can
  • 01
    Explain the missing valueShow with FormData why an input inside a shadow root never reaches the page's form.
  • 02
    Make an element join its formUse static formAssociated = true, attachInternals(), a name, and setFormValue(), and read form and labels.
  • 03
    Pick 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:

An order form with a number box in a shadow rootPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
tea-cups.js: a number box inside a shadow rootJavaScript
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.js tab, line 4 attaches a shadow root. Line 5 puts the number box in it, named cups, 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:

tea-cups.js: a form-associated custom elementJavaScript
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);
The same order form, with the name on the hostPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Two halves. On the left, before: a card tea Sencha, and a crate labelled shadow root, inside tea-cups, holding a faded, crossed-out card cups 2. An arrow from tea Sencha leads to a card FormData: tea Sencha. Outcome: cups never sent. On the right, after: the same tea card, and the same crate holding the card box: 2. The arrow leads to FormData: tea Sencha, cups 2. Outcome: cups sent.Beforetea Senchacups 2shadow rootinside tea-cupsFormData: tea Senchacups never sentAftertea Senchabox: 2shadow rootinside tea-cupsFormData: tea Sencha, cups 2cups sent
Before, the box sits in the shadow root of tea-cups, and the form can't see it. After, the host itself is the form control. It hands the form the box's value, so the form sends cups 2.
Real-life analogyA sealed tea tin

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 from setFormValue()
The main idea

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:

Playground: where does the box live?
A form that counts its controlsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The form finds the box

The box is a child of the form, so the form is its form owner. form.elements counts it, and FormData has its value.

Only line 3 changes. The tea-cups.js tab is the one from the overview.
  • 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, and cups 2.
  • In a shadow root: Controls: 1 and tea 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:

A box in a shadow root that names its form by idPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In the tea-cups.js tab, line 5 now ends with form="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.

tea-cups.js with form="order" on the boxJavaScript
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.

How Chrome picks a form owner, shortened from listed_element.cc lines 357 to 400C++
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:

  1. Line 3 reads the control's form attribute, if it has one.
  2. Line 4 finds the nearest form among its parents. FindFormAncestor() walks up parent by parent, and a shadow root has no parent.
  3. Lines 7 to 10 run when there is a form attribute. Line 9 looks up the id with GetTreeScope(): the control's own tree. Line 10 keeps it only if it's a form.
  4. Line 13 runs when there is no form attribute. It takes the nearest form from line 4.
  5. 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:

The flag in the class, and the flag set too latePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 2 and 3 are two tags in a form.
  • Lines 6 to 8 give TeaCups the flag, as a static field. Line 9 makes TeaSugar without 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.

Real-life analogySigning up for a stall at the market

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 by define()
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 formAssociated after define()

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:

The four attributes of a form-associated element
AttributeWhat the browser does with it
nameIt names the entry the form sends, and finds the element in form.elements. With no name, or an empty one, nothing is sent.
disabledIt 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.
formIt gives the element to the form with that id in the same tree, instead of the form around it.
readonlyIt 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:

tea-cups.js: a form-associated stand-in with the value 2JavaScript
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: form and labels. More on those soon.

Now try three of the attributes on it:

Playground: which attributes does the host have?
The stand-in with different attributesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Sent under its name

The host has a name and a value, so the form sends cups 2, right after the tea. It isn't disabled.

Only line 3 changes.
  • Line 9 prints each entry the form would send.
  • Line 10 asks if the host matches :disabled.
  • name="cups": cups 2 is sent.
  • No name: nothing is sent for the cups.
  • disabled: nothing is sent, and it prints Disabled: true.
  • readonly: cups 2 is 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:

Playground: the internals with and without the flag
An element that tries four members of its internalsPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups></form><script src="tea-cups.js"></script>
ResultLoading…
Try it yourself
The ARIA part works, the form part throws

attachInternals() works on any autonomous custom element, so role works. form, labels, and validity throw a NotSupportedError, because the element isn't form-associated.

The page stays the same. Only line 2 of the tea-cups.js tab changes.
  • In the tea-cups.js tab, 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, then form, labels, and validity each print NotSupportedError.
  • 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 ElementInternals holds for a form control
What the internals holdWhat it's forWhere the course teaches it
form and labelsThe 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 propertiesA default role and states for screen readers.Lesson 13.2.
statesCustom states that CSS reads with :state().Lesson 12.3.
shadowRootThe 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.

Real-life analogyA note on the order board

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:

  1. If it has a form attribute, its owner is the form with that id, in its own tree. If there is no such form, it has no owner at all.
  2. 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:

Playground: where does tea-cups sit?
tea-cups in or near the order formPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The nearest form around it

No form attribute, so the cups take the nearest form element they sit in: order. The order form sends them.

Only lines 3 and 5 change. The tea-cups.js tab is the stand-in.
  • 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 form getter 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.
Two halves. On the left, in the page: a card tea-cups name="cups" at the bottom, and an arrow climbing up to a card form id="order", marked nearest form. Outcome: form owner: order. On the right, in a shadow root: the card tea-cups form="order" with a short arrow up to a card shadow root. Above it, a gap with the note the climb stops here, then the card form id="order", out of reach. Outcome: form owner: null.In the page<form id="order">nearest form<tea-cups name="cups">form owner: orderIn a shadow root<form id="order">the climb stops hereshadow root<tea-cups form="order">form owner: null
On the left, tea-cups climbs its parents to the nearest form. On the right, it sits in a shadow root. The climb ends at the root, and form="order" only looks inside that root. So it has no form.
Real-life analogySeat cards at a wedding

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:

The stand-in, found by its name, with a labelPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 is a label for cups. Line 3 is the stand-in, with that id and the name cups.
  • 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 labels getter in the tab.
  • Line 11 reads a name property.

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:

An order form with an interactive switch and a containerPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
tea-toggle.js: a switch that is the controlJavaScript
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 switch and 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 checked state, which the page's CSS colors. Line 26 hands the form "on", or null when it's off.
tea-cups.js as a container that delegates focusJavaScript
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.

Two halves. On the left, the host is the control: a card tea-toggle name="milk", with two cards under it, role: switch and focus: the host, and the line milk on, which the host sends. On the right, the host wraps a control: a card tea-cups name="cups", with a crate labelled shadow root under it holding a card input: role, focus, and the line cups 2, which the host sends.The host is the control<tea-toggle name="milk">role: switchfocus: the hostmilk onthe host sends itThe host wraps a control<tea-cups name="cups">input: role, focusshadow rootcups 2the host sends it
On the left, the switch's host has the role and takes focus. On the right, the input inside the shadow root has them. Either way, only the host can reach the form, so the host sends the value.
Real-life analogyA ticket machine and a ticket booth

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: delegatesFocus sending 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:

Two designs of form control
QuestionWhen the host is the controlWhen 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:

The order form with the kit's quantityPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

The lines kitAfter161 adds to tea-quantity.jsJavaScript
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 form and name properties, 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:

Does it reach FormData?
  • <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 no formAssociated.
Try it yourself
0 of 7 correct

Sort each control by whether the order form sends it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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

Exercise 1 · Warm-upCount the controls

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upCups with no name

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeTurn on form association

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeCups in the sidebar

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeSend the switch's value

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeBring the cups back to the form

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The form-associated elements quiz · 7 questionsScore: first tries count
              1. Question 1 of 7The box sits in a shadow root, with form="order". What does this page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              2. Question 2 of 7A class has no formAssociated. Which members of its internals throw a NotSupportedError?

                Choose an answer to see the explanation.

              3. 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.

              4. 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.

              5. Question 5 of 7What does readonly do on a form-associated element, if its class adds nothing?

                Choose an answer to see the explanation.

              6. 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.

              7. 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 = true makes the host a form control: listed, submittable, resettable, and labelable. define() reads it once.
              • attachInternals() works without the flag, but form, labels, and the rest of the form part need it.
              • setFormValue() gives the form its value. null sends nothing, and every element starts there.
              • A control's form is the nearest <form> among its parents, or the one its form attribute names in its own tree.
              • name names the entry. disabled leaves it out. readonly only 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:

              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.

              CompleteFrontend Clear concepts. Working examples.