Form-associated custom element
Learn form association with ElementInternals and the form attribute.
Form-associated custom element
Plain custom elements don't take part in form data; form-associated custom elements act like form participants. The class sets static formAssociated = true and calls attachInternals() to get an ElementInternals object.
On the HTML side, one attribute is enough: form. A custom element placed outside a form joins it by writing form="register", just like <button form="...">. Layout stays flexible.
Value and validation with ElementInternals
ElementInternals is the bridge between a custom element and its form. In JS, internals.setFormValue() sends a value and internals.setValidity() reports validation state. The browser reflects this onto form submission and the :invalid pseudo-class.
On the HTML side, the form attribute and a name are enough. For example, <rating-input form="register" name="rating"> sets a proper field name; the JS side produces the value, the HTML side sets the context.
Exercise Write a form-associated custom element outside the form
Open a <form id="register">. Inside it:
- A
<label for="email">with non-empty content - An
<input id="email" name="email" type="email"> - A
<rating-input form="register" name="rating">(inside or outside the form) - A
<button type="submit">with non-empty content
The form should include the outside custom element via the form attribute.
Show example solution
<form id="register" action="/register" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<rating-input form="register" name="rating"></rating-input>
<button type="submit">Save</button>
</form>
Test yourself
-
Which HTML attribute binds a custom element to an outside form?
<rating-input ??="register" name="rating"></rating-input>- for
- name
- aria-form
- form
Show answer
form — Correct. The form attribute binds the custom element to the form with that id.
-
Complete the form attribute value
<rating-input form="____" name="rating"></rating-input>Show answer
<rating-input form="register" name="rating"></rating-input> -
Match each form feature to its meaning
- form
- Binds outer form
- name
- Sets field name
- formAssociated
- JS flag
- setFormValue
- Sends value