completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Form values

Learn setFormValue() in ElementInternals: send a string, a File, or several values with FormData from a web component, and keep a state to restore.

By the end, you can
  • 01
    Pass the right kind of valueHand setFormValue() a string, a File, a FormData, or null, and say what the form's FormData gets for each.
  • 02
    Keep a statePass what the person typed as the state, and say why the browser keeps it but never sends it.
  • 03
    Keep the form up to dateHand the form a new value on every change, and say where the formdata event still fits.

What does setFormValue() do?

Leaf and Kettle's order form sends the cups now. In lesson 16.1, Ravi made his tag a form control, and it handed the form one string, like 2. Now Meena wants three more things on the form:

  • a blend, where you tick two or three teas and the kitchen mixes them;
  • a pickup time, typed the way people say it, like 5 pm;
  • a gift tin, with your own words on its label.

Ravi has questions. Can one element send two teas? Can it send a file? And the kitchen's clock says 17:00, but Asha typed 5 pm. Which one should the form send?

setFormValue() hands a form-associated element's value to its form. The value can be a string, a File, a FormData with several entries, or null for nothing. The form sends the last one you passed. A second argument, the state, stays with the browser so it can restore the control later. It's never sent.

Here is the blend, as a small stand-in. Its class is in the tea-blend.js tab:

An order form with a blend that sends two teasPop out in the code editor (opens in a new tab)HTML
<form id="order">  <input name="cups" value="2">  <tea-blend name="tea"></tea-blend></form><script src="tea-blend.js"></script><script>  const form = document.querySelector("#order");  for (const [name, value] of new FormData(form)) console.log(name, value);</script>
ResultLoading…
tea-blend.js: one FormData with two teasJavaScript
class TeaBlend extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  constructor() {
    super();
    const teas = new FormData();
    teas.append("tea", "Sencha");
    teas.append("tea", "Jasmine");
    this.#internals.setFormValue(teas);
  }
}
customElements.define("tea-blend", TeaBlend);
  • On the page, line 2 is a plain input named cups. Line 3 is the blend.
  • In the tab, lines 2 and 3 make the class form-associated and get its internals, as in lesson 16.1.
  • Line 7 makes an empty FormData: a list of names and values, the same kind of list new FormData(form) gives you. Lines 8 and 9 add two entries, both named tea.
  • Line 10 hands the whole list to the form.
  • Back on the page, line 8 prints every entry the form would send.

It prints cups 2, tea Sencha, and tea Jasmine. One element sent two entries. Each kind of value has its own rule. Here are all four at once:

Four rows. On the left, what an element passes to setFormValue(); on the right, what FormData gets. setFormValue("2") gives one card, cups 2. setFormValue(file) gives one card, label: a File. setFormValue(teas) gives two cards, tea Sencha and tea Jasmine. setFormValue(null) gives a faded, crossed-out card, no entry.What the element passesWhat FormData getssetFormValue("2")cups 2setFormValue(file)label: a FilesetFormValue(teas)tea Senchatea JasminesetFormValue(null)no entry
Each row is one element with a name. A string or a File becomes one entry under that name. A FormData adds each of its own entries. null adds nothing.
Real-life analogyPosting letters at the post office counter

Ravi takes the shop's post to the counter. A single letter gets the shop's address label. A bundle of letters that are already addressed goes out as it is, each to its own address. If Ravi comes with empty hands, nothing goes out.

In real life: One letter, with the shop's address label stuck on
In JavaScript: A string or a File, sent under the host's name
In real life: A bundle of letters, each already addressed
In JavaScript: A FormData, whose entries keep their own names
In real life: Coming to the counter with empty hands
In JavaScript: setFormValue(null)
In real life: The clerk who sorts the post
In JavaScript: The browser, building the form's entries
The main idea

Hand the form your element's value with setFormValue(). Pass a string, a File, a FormData, or null. The form sends the last value you passed. The second argument, the state, stays with the browser for restoring the control.

Why it matters: the kitchen gets only what you hand over, in the shape you hand it.

setFormValue() works in Chrome 77, Firefox 98, and Safari 16.4 and later. web-features lists form-associated custom elements as Baseline widely available, so every current browser has it. It's one of the methods on ElementInternals, which MDN lists with the rest.

What can you pass to setFormValue()?

Every form-associated element has two slots inside the browser. One is its value: what the form sends. The HTML Standard calls it the submission value. The other is its state, which the next section covers. Both start as null. Each call to setFormValue() fills both.

The value is the first argument. MDN lists three kinds: a string, a File, or a FormData. null is the fourth, for no value. What about anything else? Try it. Only line 7 of the tea-pick.js tab changes:

Playground: what does the form get?
A form that prints what one element sendsPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-pick name="tea"></tea-pick></form><script src="tea-pick.js"></script><script>  const form = document.querySelector("#order");  for (const [name, value] of new FormData(form)) {    const shown = value instanceof File ? `a File named ${value.name}` : JSON.stringify(value);    console.log(name, shown);  }  console.log("Entries:", [...new FormData(form)].length);</script>
ResultLoading…
Try it yourself
A string is one entry

The form sends one entry: the host's name, tea, and the string.

Only line 7 of the tea-pick.js tab changes. The page stays the same.
  • In the tea-pick.js tab, line 7 hands the form one value.
  • On the page, lines 7 to 10 print each entry. Line 8 shows a string in quotes, so you can see an empty one. A File shows its name.
  • Line 11 prints how many entries there are.
  • "Sencha": tea "Sencha", one entry.
  • 3: tea "3". The number became text.
  • The array: tea "Sencha,Jasmine". One entry, not two.
  • The File: tea a File named tin-label.txt.
  • "": tea "". Still one entry.
  • null: Entries: 0.

So anything that isn't a File, a FormData, or null is turned into a string first. It's the usual way JavaScript makes text from a value: String(3) is "3", and an array becomes its items with commas between them. And the value can't be left out. Call setFormValue() with nothing, and Chrome throws a TypeError: "1 argument required".

An empty string and null are not the same. "" sends the name with an empty value, as an empty text box does. null sends nothing at all. The switch in lesson 16.1 used that: it passed "on" while on, and null while off.

Why it matters: a number arrives as text, and an array arrives as one entry. To send several values, pass a FormData.

What is the state argument of setFormValue()?

Now the pickup time. Asha types 5 pm. The kitchen's system wants 17:00. And if she comes back to the page later, the box should still say 5 pm, the way she typed it.

That's what the second argument is for. The value is what the server gets. The state is what the person did, so the control can show it again. Here is the pickup control. Its class is in the tea-pickup.js tab:

An order form with a pickup timePop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-pickup name="pickup"></tea-pickup>  <button>Order</button></form><script src="tea-pickup.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("pickup:", new FormData(form).get("pickup"));  });</script>
ResultLoading…
tea-pickup.js: send 17:00, keep 5 pmJavaScript
class TeaPickup extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  constructor() {
    super();
    this.attachShadow({ mode: "open" }).innerHTML =
      '<label>Pickup <input placeholder="5 pm"></label>';
    const box = this.shadowRoot.querySelector("input");
    box.addEventListener("input", () => {
      const pm = box.value.match(/^([1-9]) pm$/);
      const time = pm ? `${Number(pm[1]) + 12}:00` : null;
      this.#internals.setFormValue(time, box.value);
    });
  }
}
customElements.define("tea-pickup", TeaPickup);
  • In the tab, lines 7 and 8 put a text box in the shadow root.
  • Line 10 runs on every change to the box.
  • Line 11 checks the text against a pattern: one digit from 1 to 9, a space, and pm. If it matches, pm[1] is that digit.
  • Line 12 turns 5 into 17:00. Text that doesn't match gives null.
  • Line 13 hands the form both: the time as the value, and the typed text as the state.
  • On the page, line 10 prints the form's pickup entry. get() gives null when there is none.

Press Order. It prints pickup: null, because nothing is typed yet. Type 5 pm and press Order: pickup: 17:00. Now type soon and press Order: pickup: null again.

Where did 5 pm go? The browser kept it, as the element's state. FormData never shows it, and the request never carries it.

A card at the top: setFormValue("17:00", "5 pm"). One arrow leads down left to a box labelled value, holding the card 17:00, with the note sent with the form. Another arrow leads down right to a box labelled state, holding the card 5 pm, with the notes kept by the browser and given back on restore.setFormValue("17:00", "5 pm")17:00value5 pmstatesent with the formkept by the browsergiven back on restore
One call fills both slots. The value, 17:00, goes with the form. The state, 5 pm, stays with the browser, which can hand it back when it restores the form.
Real-life analogyThe waiter's notepad and the kitchen ticket

Asha tells the waiter she'll pick up her tea at five. The waiter writes a ticket for the kitchen: 17:00. In his notepad, he keeps her own words. When Asha comes back to change her order, he reads the notepad, not the ticket.

In real life: The kitchen ticket: Sencha, 17:00
In JavaScript: The value, 17:00
In real life: The waiter's notepad, in Asha's own words
In JavaScript: The state, 5 pm
In real life: The kitchen
In JavaScript: The server
In real life: Reading the notepad when Asha comes back
In JavaScript: The browser handing the state back when it restores the form

Why keep it at all? To give it back. The HTML Standard lets the browser restore a form, for example after you leave the page and come back. It then hands each form-associated element its state, through a callback named formStateRestoreCallback(). Autofill can hand one back too. On a real page, Chrome hands back 5 pm after the Back button. With soon, it hands back soon, though nothing was ever sent. Lesson 16.4 writes that callback.

And with only one argument? Then the state is the same as the value. The steps for setFormValue() say so, and Chrome's setFormValue() shows it. You don't need to know C++ to follow it:

How Chrome stores the value and the state, shortened from element_internals.cc lines 116 to 147C++
void ElementInternals::setFormValue(const V8ControlValue* value,                                    ExceptionState& exception_state) {  setFormValue(value, value, exception_state);} void ElementInternals::setFormValue(const V8ControlValue* value,                                    const V8ControlValue* state,                                    ExceptionState& exception_state) {  if (!IsTargetFormAssociated()) {    // ...  }   if (value && value->IsFormData()) {    value_ = MakeGarbageCollected<V8ControlValue>(        MakeGarbageCollected<FormData>(*value->GetAsFormData()));  } else {    value_ = value;  }   if (value == state) {    state_ = value_;  } else if (state && state->IsFormData()) {    // ...  } else {    state_ = state;  }  // ...}

In plain words, line by line:

  1. Lines 1 to 4 are setFormValue() with one argument. Line 3 calls the other one, with the value twice.
  2. Lines 9 to 11 throw lesson 16.1's NotSupportedError if the element isn't form-associated.
  3. Lines 13 to 15 copy a FormData value. Line 17 keeps any other value as it is, in value_.
  4. Lines 20 and 21 run when the value and the state are the same thing: the one-argument case. The state is the stored value.
  5. Line 22 catches a FormData state, which is copied in the part left out. Line 25 keeps any other state, in state_.

WebKit's setFormValue() does the same. MDN gives a checkbox as its example: setFormValue("on", "checked"). The server gets on, and the browser remembers that the box was ticked. The table puts the two slots side by side. Read each row across:

The value and the state
QuestionThe valueThe state
What is it for?What the server gets, in the form it wants, like 17:00.What the person did, like typing 5 pm, so the control can show it again.
Is it sent with the form?Yes, under the rules in the next section.No. The browser keeps it.
Who reads it?FormData, and every submit.The browser, when it restores the form. It hands the state to formStateRestoreCallback().
What if you leave it out?You can't. Chrome throws a TypeError.It becomes the same as the value.
What is it at first?null.null.

Why it matters: give the server clean data, and give the browser what the person did. Then a restored form looks the way they left it.

What does FormData receive from a custom element?

The browser builds a form's entries in one pass. It does it for new FormData(form), and for every submit. It walks the form's controls in page order, and skips disabled ones, as the HTML Standard's list-building steps say. For a form-associated element, its entry construction steps do the rest. Together, that's four rules:

  1. A disabled element gives nothing.
  2. A null value gives nothing.
  3. A FormData value gives each of its entries, under the entries' own names. The host's name isn't read. It isn't even needed.
  4. A string or a File needs a name. With no name, or an empty one, it gives nothing. With a name, it gives one entry.

Rule 3 surprises people. Try all four rules with two stand-ins in one form. tea-cups hands over the string 2. The blend from the overview hands over its FormData. Only lines 2 and 3 change:

Playground: names and disabled
A form with a string and a FormDataPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups>  <tea-blend name="blend"></tea-blend></form><script src="tea-cups.js"></script><script src="tea-blend.js"></script><script>  const form = document.querySelector("#order");  for (const [name, value] of new FormData(form)) console.log(name, value);  console.log("Entries:", [...new FormData(form)].length);</script>
ResultLoading…
Try it yourself
The string takes the host's name, the FormData doesn't

tea-cups sends its string under its own name, cups. tea-blend is named blend, but its entries keep their own name, tea. The browser never reads "blend".

Only lines 2 and 3 change. The tea-blend.js tab is the overview's.
  • Lines 2 and 3 are the two elements and their attributes.
  • Line 9 prints each entry. Line 10 prints how many there are.
  • Both named: cups 2, tea Sencha, and tea Jasmine. The blend is named blend, but its entries say tea.
  • No names: only the two teas.
  • Both disabled: Entries: 0.

Back at the post office counter, it's the bundle of letters: they already have their addresses, so the shop's label isn't needed.

Chrome follows the same rules, in the same order. The form calls AppendToFormData() for every control it owns, from ConstructEntryList():

How Chrome adds a custom element's entries, shortened from element_internals.cc lines 583 to 629C++
void ElementInternals::AppendToFormData(FormData& form_data) {  if (Target().IsDisabledFormControl()) {    return;  }   // ...  if (!value_) {    return;  }   const AtomicString& name = Target().FastGetAttribute(html_names::kNameAttr);  if (!value_->IsFormData() && name.empty()) {    return;  }   switch (value_->GetContentType()) {    case V8ControlValue::ContentType::kFile: {      form_data.AppendFromElement(name, value_->GetAsFile());      break;    }    case V8ControlValue::ContentType::kUSVString: {      form_data.AppendFromElement(name, value_->GetAsUSVString());      break;    }    case V8ControlValue::ContentType::kFormData: {      for (const auto& entry : value_->GetAsFormData()->Entries()) {        if (entry->isFile())          form_data.append(entry->name(), entry->GetFile());        else          form_data.append(entry->name(), entry->Value());      }      break;    }  }}

In plain words, line by line:

  1. Lines 2 to 4: a disabled element stops here. That's rule 1.
  2. Lines 7 to 9: no value means nothing to add. That's rule 2.
  3. Line 11 reads the host's name attribute. Line 12 stops when the value isn't a FormData and the name is empty. A missing name counts as empty. That's rule 4.
  4. Lines 17 to 24 add a File or a string once, under the host's name.
  5. Lines 25 to 31 add a FormData's entries one by one. Lines 28 and 30 use entry->name(): each entry's own name. That's rule 3.

The table puts every case side by side. Read each row across:

What the form gets for each kind of value
What you passOn a host with a nameOn a host with no nameOn a disabled host
A string, like "2"One entry: the host's name and the string.Nothing.Nothing.
A FileOne entry: the host's name and the File.Nothing.Nothing.
A FormDataEach of its entries, under its own name. The host's name isn't used.Each of its entries, under its own name.Nothing.
nullNothing.Nothing.Nothing.

Where do the entries go in the list? In page order, with the other controls. The overview printed cups 2 first because its input comes before the blend.

Why it matters: when a value goes missing, check three things. Is the host disabled? Is the value null? Does a string or a File have a name?

How do you send a file or several values?

Several values under one name

A blend is several teas. A <select multiple> already sends several values: one entry for each chosen option, all under its name. A custom element does the same with a FormData. Here is a real blend, with a checkbox for each tea:

An order form with a checkbox blendPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-blend name="tea"></tea-blend>  <button>Order</button></form><script src="tea-blend.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("tea:", new FormData(form).getAll("tea").join(", ") || "none");  });</script>
ResultLoading…
tea-blend.js: one entry for each ticked teaJavaScript
class TeaBlend extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  constructor() {
    super();
    this.attachShadow({ mode: "open" }).innerHTML = `
      <label><input type="checkbox" value="Sencha"> Sencha</label>
      <label><input type="checkbox" value="Jasmine"> Jasmine</label>
      <label><input type="checkbox" value="Oolong"> Oolong</label>`;
    this.shadowRoot.addEventListener("change", () => {
      const teas = new FormData();
      for (const box of this.shadowRoot.querySelectorAll(":checked")) {
        teas.append(this.getAttribute("name"), box.value);
      }
      this.#internals.setFormValue(teas);
    });
  }
}
customElements.define("tea-blend", TeaBlend);
  • In the tab, lines 7 to 10 put three checkboxes in the shadow root.
  • Line 11 listens for change. Every tick fires it at the box, and it bubbles up to the shadow root.
  • Line 12 starts a new FormData. Lines 13 to 15 add one entry for each ticked box. Line 14 names each entry after the host's name attribute.
  • Line 16 hands the list to the form.
  • On the page, line 10 prints every tea. getAll() gives every value under one name, as in the JavaScript lesson on FormData.

Press Order: tea: none. Tick Sencha and Jasmine, and press Order again: tea: Sencha, Jasmine.

Why does line 14 name the entries itself? Because of rule 3: the browser won't name them for you. So the entries can have any names. A pickup control could send pickup-day and pickup-time from one element. web.dev's guide builds each name from the host's name and a word. Exercise 5 shows what line 14 does when the host has no name at all.

The FormData is copied

The browser keeps a copy of a FormData value, made at the call. Lines 13 to 15 of Chrome's setFormValue() did that, and the HTML Standard calls it a clone. So changing your FormData later changes nothing:

Adding to a FormData after handing it overPop out in the code editor (opens in a new tab)HTML
<form id="order"><tea-blend name="tea"></tea-blend></form><script>  class TeaBlend extends HTMLElement {    static formAssociated = true;    internals = this.attachInternals();  }  customElements.define("tea-blend", TeaBlend);  const blend = document.querySelector("tea-blend");  const teas = new FormData();  teas.append("tea", "Sencha");  blend.internals.setFormValue(teas);  teas.append("tea", "Jasmine");  const form = document.querySelector("#order");  console.log("Sent:", new FormData(form).getAll("tea").join(", "));</script>
ResultLoading…
  • Line 5 keeps the internals in a public field, so the page's script can reach them. Real components keep them private.
  • Lines 9 to 11 hand the form a FormData with Sencha in it.
  • Line 12 adds Jasmine to the same FormData, after the call.
  • Line 14 prints Sent: Sencha. The form never saw Jasmine.
Real-life analogyHanding in a photocopy of your list

At the shop's counter, Meena takes a photocopy of your order list and keeps it. If you write milk on your own list later, her copy doesn't change. To add milk, you hand in a new copy.

In real life: Your shopping list
In JavaScript: The FormData you built
In real life: The photocopy the shop keeps
In JavaScript: The value the browser stores
In real life: Writing milk on your own list later
In JavaScript: teas.append() after setFormValue()
In real life: Handing in a new photocopy
In JavaScript: Calling setFormValue() again

So build a fresh FormData each time, as line 12 of the blend does, and hand it over again.

Sending a file

Now the gift tin. A File is data with a file name and a type, as the JavaScript lesson showed in sending files. You can make one in code with new File(parts, name, options). A form-associated element can hand a File to its form:

An order form with a gift tin labelPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-tin name="label"></tea-tin>  <button>Order</button></form><script src="tea-tin.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", async (event) => {    event.preventDefault();    const file = new FormData(form).get("label");    console.log("File:", file.name, file.type);    console.log("It holds:", await file.text());  });</script>
ResultLoading…
tea-tin.js: the label, sent as a fileJavaScript
class TeaTin extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  constructor() {
    super();
    this.attachShadow({ mode: "open" }).innerHTML =
      '<label>Label <input value="Leaf and Kettle"></label>';
    const box = this.shadowRoot.querySelector("input");
    const send = () => {
      const file = new File([box.value], "tin-label.txt", { type: "text/plain" });
      this.#internals.setFormValue(file);
    };
    send();
    box.addEventListener("input", send);
  }
}
customElements.define("tea-tin", TeaTin);
  • In the tab, line 8 puts a text box in the shadow root, holding Leaf and Kettle.
  • Line 11 makes a File from the box's text, named tin-label.txt, with the type text/plain.
  • Line 12 hands it to the form. Line 14 does that once, at the start, and line 15 on every change.
  • On the page, line 10 gets the File back. Line 11 prints its name and type. Line 12 reads what it holds with text().

Press Order. It prints File: tin-label.txt text/plain, then It holds: Leaf and Kettle. Type Asha's tin in the box, and press Order again: It holds: Asha's tin. A real upload control would put an <input type="file"> in its shadow root, and hand the form input.files[0], the file the person picked.

What the server gets

FormData isn't what travels. When a form is sent, the browser turns its entries into the body of a request. The course sent a form for real, with method="post". It held the cups input, the two-tea blend from the overview, the tin, and the pickup, with 5 pm typed in. With no enctype, Chrome sent this body:

The request body with the default enctypeText
cups=2&tea=Sencha&tea=Jasmine&label=tin-label.txt&pickup=17%3A00
  • tea comes twice, once for each entry.
  • label is only the file's name. This format has room for text alone, so the HTML Standard swaps a File for its name.
  • pickup is 17:00, with the colon written as %3A. And 5 pm is nowhere: the state never travels.

To send what the file holds, the form needs enctype="multipart/form-data". Then each entry gets a part of its own:

The same form with enctype="multipart/form-data"Text
--BOUNDARY
Content-Disposition: form-data; name="cups"

2
--BOUNDARY
Content-Disposition: form-data; name="tea"

Sencha
--BOUNDARY
Content-Disposition: form-data; name="tea"

Jasmine
--BOUNDARY
Content-Disposition: form-data; name="label"; filename="tin-label.txt"
Content-Type: text/plain

Leaf and Kettle
--BOUNDARY
Content-Disposition: form-data; name="pickup"

17:00
--BOUNDARY--

BOUNDARY stands for a random line Chrome makes up for each request. The label's part has the file name, the type, and Leaf and Kettle.

Why it matters: a form with a file needs enctype="multipart/form-data". Without it, the server gets a file name and no file.

When should you call setFormValue()?

Nothing ever asks your element for its value. The browser reads what you last handed it, at the moment it builds the form's entries. That can happen at any time: on a submit, in any script that calls new FormData(form), or in form.submit(). So hand the form a new value every time the value changes.

Here is what goes wrong otherwise. This tea-cups has a + button. The page has two buttons: Check builds the entries without sending, and Order sends. For each choice, press + twice, then Check, then Order. Only lines 13 and 17 of the tab change:

Playground: when does tea-cups tell the form?
A form with a + button, Check, and OrderPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-cups name="cups"></tea-cups>  <button type="button" id="check">Check</button>  <button>Order</button></form><script src="tea-cups.js"></script><script>  const form = document.querySelector("#order");  const show = (when) => console.log(when, new FormData(form).get("cups"));  document.querySelector("#check").addEventListener("click", () => show("Check:"));  form.addEventListener("submit", (event) => {    event.preventDefault();    show("Order:");  });</script>
ResultLoading…
Try it yourself
The form keeps the first number

Line 9 hands the form 1, and nothing hands it a new number. Check and Order both read 1, while the box shows 3.

The page stays the same. Only lines 13 and 17 of the tea-cups.js tab change.
  • In the tea-cups.js tab, line 9 hands the form 1 at the start. Lines 10 to 14 add one on each click, and show the new number.
  • Line 13 is where a click could tell the form. Line 17 is where the element could wait for the form's submit event.
  • On the page, line 9 prints the form's cups entry. Line 10 runs it for Check, and line 13 for Order.
  • Only at the start: Check: 1 and Order: 1, while the box shows 3.
  • When the form is sent: Check: 1, then Order: 3.
  • On every change: Check: 3 and Order: 3.

The middle one looks right, until something reads the form at another time. And form.submit() doesn't fire a submit event at all: the HTML Standard skips it. The course sent that version with form.submit() after two presses, and Chrome sent cups=1.

Two rows, each pressing plus twice. Top row, Only at the start: the screen shows 1, 2, 3. The form holds 1, 1, 1. Check prints Check: 1, so the form is behind. Bottom row, On every change: the screen shows 1, 2, 3, and so does the form. Check prints Check: 3, so the form keeps up.Only at the starton screenin the form123++111Check: 1the form is behindOn every changeon screenin the form123++123Check: 3the form keeps up
Both rows press + twice, then Check. When the element tells the form only at the start, the form still says 1. When it tells the form on every click, the form says what the screen says.
Real-life analogyThe scoreboard at a cricket match

At a cricket match, the scorer changes the board after every run. Anyone can look up at any moment and see the score. If the scorer waited until the end of the game, the board would be wrong the whole afternoon.

In real life: The number on the board
In JavaScript: The value the browser stores
In real life: Changing the board after every run
In JavaScript: setFormValue() on every change
In real life: Anyone looking up at the board
In JavaScript: A submit, new FormData(form), or form.submit()
In real life: Waiting until the end of the game
In JavaScript: Calling setFormValue() only on submit

Every path that changes the value must hand it over: the person's clicks and typing, a property the page sets, and an attribute it changes. Burton Smith and Caleb Williams call setFormValue() on every input. The WebKit blog's example calls it in attributeChangedCallback(), and so does exercise 6. It's lesson 16.1's order board again: Ravi reads whichever note is pinned when the order goes out.

Where does the formdata event fit?

A control can also add its value from the form's formdata event. The browser fires that event at the end of building the entries, with the list in event.formData. A listener can add to the list. web.dev's guide shows that route next to form association, and the JavaScript lesson covers the formdata event.

It still works, but it only adds entries. It touches nothing but the submission: the control gets no labels, no validation, and no reset. So today it suits extra data for the whole form, like where an order came from:

The formdata event adds one more entryPop 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></form><script src="tea-cups.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("formdata", (event) => {    event.formData.append("source", "web");  });  for (const [name, value] of new FormData(form)) console.log(name, value);</script>
ResultLoading…
  • Line 3 is the tea-cups stand-in, which hands over the string 2.
  • Line 8 listens for formdata. Line 9 adds source with the value web.
  • Line 11 builds the entries, which fires the event, and prints them.

It prints tea Sencha, cups 2, then source web. The controls come in page order, and the event's entry comes last. Chrome's ConstructEntryList() asks every control first, then fires the event.

Why it matters: hand over the value on every change, from every path. Keep formdata for data that belongs to the whole form.

Adding a tea blend to the order form

The kit grows. Its new version, kitAfter162, adds tea-blend, a real blend builder. It also gives tea-quantity a value setter. Here is the order form with both:

The order form with the kit's blend and quantityPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order">  <tea-blend name="tea" label="Blend"><option selected>Sencha</option><option>Jasmine</option><option>Oolong</option></tea-blend>  <label for="cups">Cups</label>  <tea-quantity id="cups" name="cups"></tea-quantity>  <button type="button" id="again">Same as last time</button>  <button>Order</button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("#order");  document.querySelector("#again").addEventListener("click", () => {    form.elements.cups.value = 3;  });  form.addEventListener("submit", (event) => {    event.preventDefault();    for (const [name, value] of new FormData(form)) console.log(name, value);  });</script>
ResultLoading…
  • Line 3 is the blend, named tea, with the label Blend. Each option becomes a checkbox. selected starts Sencha ticked.
  • Lines 4 and 5 are the label and the quantity from lesson 16.1.
  • Lines 12 to 14 set the quantity to 3 from script. That's what Asha had last time.
  • Lines 15 to 18 print the entries on Order.

Press Order: tea Sencha and cups 1. Tick Jasmine, press Same as last time, then Order: tea Sencha, tea Jasmine, and cups 3. Here are the lines of tea-blend.js that hand the form its value:

How tea-blend.js hands the form its teasJavaScript
  static formAssociated = true;
  static observedAttributes = ["name", "label"];
// ... in the constructor, every tick sends the new value:
    this.shadowRoot.addEventListener("change", () => this.#send());
// ... in attributeChangedCallback(), so does a new name:
    else this.#send();
// ...
  #send() {
    const name = this.getAttribute("name");
    const teas = this.value;
    if (!name || teas.length === 0) {
      this.#internals.setFormValue(null);
      return;
    }
    const entries = new FormData();
    for (const tea of teas) entries.append(name, tea);
    this.#internals.setFormValue(entries);
  }
  • Lines 1 and 2: it's form-associated, and it watches its name.
  • Line 4: every tick runs #send(). Line 6: so does a new name.
  • Lines 9 to 14: with no name, or no tea ticked, it hands the form null. Rule 3 means the browser won't check the name for a FormData, so the blend checks it.
  • Lines 15 to 17: one entry for each ticked tea, all under the host's name, in one FormData.

And the quantity's new setter:

The value setter kitAfter162 adds to tea-quantity.jsJavaScript
  set value(cups) {
    const value = Math.round(Number(cups));
    this.#value = Number.isFinite(value) && value > 1 ? value : 1;
    this.shadowRoot.querySelector("output").textContent = this.#value;
    this.#internals.setFormValue(String(this.#value));
  }
  • Line 2 turns whatever it's given into a whole number. Line 3 keeps it at 1 or more.
  • Line 4 shows it. Line 5 hands it to the form. Without line 5, script could change the number on screen and leave the form behind.

Like a native input changed from script, the setter fires no quantity-change event. In Chrome's accessibility tree, the blend is a group named Blend, with a checkbox for each tea. Its JSDoc and custom-elements.json document the new tag and the setter. The course's test runs pages from earlier lessons with both versions of the kit, and every printed line, box, and tree stays the same.

Now sort some calls by what the form gets:

What does the form get?
  • setFormValue("2") on a host named cups.
  • setFormValue(["Sencha", "Jasmine"]) on a host named tea.
  • setFormValue("") on a host named note.
  • setFormValue("17:00", "5 pm") on a host named pickup.
  • A FormData with two tea entries, on a host with no name.
  • A File, on a host with no name.
  • A FormData with two tea entries, on a disabled host.
  • setFormValue(null) on a host named cups.
Try it yourself
0 of 8 correct

Sort each call by how many entries the form gets from 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 order form now sends a whole blend, and a quantity set by script, with no extra code.

Common mix-ups

  • "The browser asks for the value when the form is sent." No. It reads the value you last passed. Call setFormValue() on every change.
  • "An array sends several values." No. It's turned into one string, Sencha,Jasmine. Use a FormData.
  • "A FormData value is sent under the host's name." No. Each entry keeps its own name. The host's name isn't read.
  • "A string value is sent even without a name." No. A string or a File needs a name. Without one, nothing is sent.
  • "The state is sent too." No. Only the value is sent. The browser keeps the state for restoring the control.
  • "Changing the FormData later changes what's sent." No. The browser keeps a copy. Call setFormValue() again.
  • "A File value always sends the file." No. Only with enctype="multipart/form-data". Otherwise the server gets its name.
  • "An empty string and null do the same." No. "" sends an empty entry. null sends nothing.
  • "Custom controls should use the formdata event." No. It only adds entries, with no labels, validation, or reset. Today it suits extra data for the whole form.

Practice exercises

Exercise 1 · Warm-upWhose name is it?

The overview's blend sits in a form, named blend. Predict what the page prints, then run it.

<form id="order">  <tea-blend name="blend"></tea-blend></form><script src="tea-blend.js"></script><script>  const form = document.querySelector("#order");  console.log("blend entries:", new FormData(form).getAll("blend").length);</script>
ResultLoading…

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

    Exercise 2 · Warm-upEmpty or nothing

    Two elements, both named. How many entries does the form have? Predict, then run it.

    <form id="order">  <tea-note name="note"></tea-note>  <tea-gift name="gift"></tea-gift></form><script>  class TeaNote extends HTMLElement {    static formAssociated = true;    constructor() {      super();      this.attachInternals().setFormValue("");    }  }  class TeaGift extends HTMLElement {    static formAssociated = true;    constructor() {      super();      this.attachInternals().setFormValue(null);    }  }  customElements.define("tea-note", TeaNote);  customElements.define("tea-gift", TeaGift);  console.log("Entries:", [...new FormData(document.querySelector("#order"))].length);</script>
    ResultLoading…

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

      Exercise 3 · PracticeTell the form about the milk

      Tick Milk and press Check. It prints milk: null. Fix the class in the tea-milk.js tab, so the form gets yes while the box is ticked. What does Check print then?

      <form id="order">  <tea-milk name="milk"></tea-milk>  <button type="button" id="check">Check</button></form><script src="tea-milk.js"></script><script>  const form = document.querySelector("#order");  document.querySelector("#check").addEventListener("click", () => {    console.log("milk:", new FormData(form).get("milk"));  });</script>
      ResultLoading…

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

        Exercise 4 · PracticeTwo teas, not one

        This blend keeps its teas in an array and passes the array. Fix the tea-blend.js tab so the form gets each tea as its own entry. How many teas does the page say were sent then?

        <form id="order">  <tea-blend name="tea"></tea-blend></form><script src="tea-blend.js"></script><script>  const teas = new FormData(document.querySelector("#order")).getAll("tea");  console.log("Teas sent:", teas.length);  for (const tea of teas) console.log(tea);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeA blend with no name

          This is the checkbox blend, with no name on the page. Tick Sencha and press Order: it sends null Sencha. Make a blend with no name send nothing. What does Order print then?

          <form id="order">  <tea-blend></tea-blend>  <button>Order</button></form><script src="tea-blend.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);    console.log("Entries:", [...new FormData(form)].length);  });</script>
          ResultLoading…

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

            Exercise 6 · ChallengeA size that changes

            The page changes the size to large, but the form still sends size small. Fix the tea-size.js tab so the form follows the attribute. What does the page print then?

            <form id="order">  <tea-size name="size" value="small"></tea-size></form><script src="tea-size.js"></script><script>  document.querySelector("tea-size").setAttribute("value", "large");  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 values quiz · 7 questionsScore: first tries count
              1. Question 1 of 7This element passes a FormData, then changes it. What does the page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <form id="order"><tea-blend></tea-blend></form>
                <script>
                  customElements.define("tea-blend", class extends HTMLElement {
                    static formAssociated = true;
                    constructor() {
                      super();
                      const teas = new FormData();
                      teas.append("tea", "Sencha");
                      this.attachInternals().setFormValue(teas);
                      teas.set("tea", "Oolong");
                    }
                  });
                  console.log(new FormData(document.querySelector("#order")).get("tea"));
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 7An element calls setFormValue("17:00"), with no second argument. What is its state?

                Choose an answer to see the explanation.

              3. Question 3 of 7An element has no name attribute. Its value is a FormData with two tea entries. What does the form send for it?

                Choose an answer to see the explanation.

              4. Question 4 of 7When does the browser read a custom element's value?

                Choose an answer to see the explanation.

              5. Question 5 of 7A custom element's value is a File. Which enctype sends what the file holds?

                Choose an answer to see the explanation.

              6. Question 6 of 7Is a form-associated element's state sent to the server?

                Choose an answer to see the explanation.

              7. Question 7 of 7What is the formdata event good for, now that custom elements have setFormValue()?

                Choose an answer to see the explanation.

              Key takeaways

              • setFormValue(value, state) fills two slots. Both start as null.
              • The value can be a string, a File, a FormData, or null. Anything else, like a number or an array, is turned into a string.
              • A string or a File is sent under the host's name, and not at all without one. A FormData's entries keep their own names. A disabled host sends nothing.
              • To send several values, pass a FormData. The browser keeps a copy, so build a new one for each change.
              • A File's contents travel only with enctype="multipart/form-data".
              • The state is what the person did. It's never sent. The browser keeps it for restoring the control. Leave it out, and it's the value.
              • Nothing asks your element for its value. Call setFormValue() on every change, from every path.
              • The formdata event now suits extra data for the whole form.

              Remember the one-liner.
              The form sends whatever you last handed setFormValue(). The state stays with the browser.

              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: Validation. It reports errors like a native input, with setValidity(), messages, and the browser's error bubble.

              CompleteFrontend Clear concepts. Working examples.