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.
- 01Pass the right kind of valueHand
setFormValue()a string, a File, a FormData, ornull, and say what the form'sFormDatagets for each. - 02Keep a statePass what the person typed as the state, and say why the browser keeps it but never sends it.
- 03Keep the form up to dateHand the form a new value on every change, and say where the
formdataevent 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:
<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>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 namedtea. - 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:
null adds nothing.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
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:
<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>The form sends one entry: the host's name, tea, and the string.
- In the
tea-pick.jstab, 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:
<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>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 givesnull. - 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
pickupentry.get()givesnullwhen 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.
17:00, goes with the form. The state, 5 pm, stays with the browser, which can hand it back when it restores the form.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:
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:
- Lines 1 to 4 are
setFormValue()with one argument. Line 3 calls the other one, with the value twice. - Lines 9 to 11 throw lesson 16.1's
NotSupportedErrorif the element isn't form-associated. - Lines 13 to 15 copy a FormData value. Line 17 keeps any other value as it is, in
value_. - 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.
- 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:
| Question | The value | The 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:
- A disabled element gives nothing.
- A
nullvalue gives nothing. - 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.
- 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:
<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>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".
- 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, andtea 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():
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:
- Lines 2 to 4: a disabled element stops here. That's rule 1.
- Lines 7 to 9: no value means nothing to add. That's rule 2.
- Line 11 reads the host's
nameattribute. 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. - Lines 17 to 24 add a File or a string once, under the host's name.
- 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 you pass | On a host with a name | On a host with no name | On a disabled host |
|---|---|---|---|
A string, like "2" | One entry: the host's name and the string. | Nothing. | Nothing. |
| A File | One entry: the host's name and the File. | Nothing. | Nothing. |
| A FormData | Each of its entries, under its own name. The host's name isn't used. | Each of its entries, under its own name. | Nothing. |
null | Nothing. | 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:
<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>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
nameattribute. - 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:
<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>- 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.
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()aftersetFormValue() - 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:
<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>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 typetext/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:
cups=2&tea=Sencha&tea=Jasmine&label=tin-label.txt&pickup=17%3A00teacomes twice, once for each entry.labelis only the file's name. This format has room for text alone, so the HTML Standard swaps a File for its name.pickupis17: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:
--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:
<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>Line 9 hands the form 1, and nothing hands it a new number. Check and Order both read 1, while the box shows 3.
- In the
tea-cups.jstab, 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
submitevent. - On the page, line 9 prints the form's
cupsentry. Line 10 runs it for Check, and line 13 for Order.
- Only at the start:
Check: 1andOrder: 1, while the box shows 3. - When the form is sent:
Check: 1, thenOrder: 3. - On every change:
Check: 3andOrder: 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.
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), orform.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:
<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>- Line 3 is the
tea-cupsstand-in, which hands over the string 2. - Line 8 listens for
formdata. Line 9 addssourcewith the valueweb. - 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:
<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>- Line 3 is the blend, named
tea, with the label Blend. Each option becomes a checkbox.selectedstarts 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:
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:
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:
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.
Sort each call by how many entries the form gets from it.
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.nullsends 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
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><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>It prints blend entries: 0. The blend's FormData holds two entries named tea. The browser adds them under that name, and never reads the host's name, blend.
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><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>It prints Entries: 1. tea-note sends note with an empty value. tea-gift passes null, so the form leaves it out.
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><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>The tea-milk.js tab adds setFormValue(box.checked ? "yes" : null) to the change listener, so every tick tells the form. Tick Milk and press Check: milk: yes.
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><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>The tea-blend.js tab builds a FormData in the constructor, appends each tea under this.getAttribute("name"), and passes it. The page prints Teas sent: 2, then Sencha and Jasmine.
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><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>The tea-blend.js tab reads the name first, and passes null when there is none. A FormData value is sent even without a host name, so the blend has to check. Order now prints Entries: 0, like an input with no name.
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><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>The tea-size.js tab observes the value attribute, and attributeChangedCallback() hands the form each new value. It runs for small when the element upgrades, and again for large. The page prints size large.
Check your understanding
Question 1 of 7This element passes a FormData, then changes it. What does the page print?
Read the code, then predict<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.
Question 2 of 7An element calls setFormValue("17:00"), with no second argument. What is its state?
Choose an answer to see the explanation.
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.
Question 4 of 7When does the browser read a custom element's value?
Choose an answer to see the explanation.
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.
Question 6 of 7Is a form-associated element's state sent to the server?
Choose an answer to see the explanation.
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 asnull.- 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
formdataevent 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:
- ElementInternals: setFormValue(), parameters, MDN.
- ElementInternals: instance methods, MDN.
- Submission value of a form-associated custom element, HTML Standard.
- The setFormValue() method steps, HTML Standard.
- State of a form-associated custom element, HTML Standard.
- ElementInternals::setFormValue(), element_internals.cc at 158.0.8127.18, Chromium.
- FormAssociatedCustomElement.cpp at WebKit-7625.2.8, WebKit.
- Entry construction for a form-associated custom element, HTML Standard.
- Constructing the entry list, HTML Standard.
- ElementInternals::AppendToFormData(), element_internals.cc at 158.0.8127.18, Chromium.
- HTMLFormElement::ConstructEntryList(), html_form_element.cc at 158.0.8127.18, Chromium.
- Converting an entry list to a list of name-value pairs, HTML Standard.
- Form submission algorithm, HTML Standard.
- Custom Forms with Web Components and "ElementInternals", Burton Smith, DEV.
- Creating Custom Form Controls with ElementInternals, Caleb Williams, CSS-Tricks.
- ElementInternals and Form-Associated Custom Elements, Ryosuke Niwa, WebKit blog.
- More capable form controls, Arthur Evans, web.dev.
- Form-associated custom elements, web-features, on Web Platform Status.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Validation. It reports errors like a native input, with setValidity(), messages, and the browser's error bubble.