Skip to content
jshacks.dev
Browser

Form-Associated Custom Elements With ElementInternals

Build custom form controls that submit and validate with form-associated custom elements and ElementInternals: setFormValue, validity, states and callbacks.

7 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Postman and NGINX logos.

A custom element made of divs and buttons looks like a form control and behaves like a stranger. It is not included in new FormData(form), it does not submit with the form, it has no name or value in the way a native input does, form.checkValidity() ignores it and form.reset() does nothing to it. Libraries solved this with a hidden <input> kept in step with the visible widget. Form-associated custom elements solve it in the platform. With one static property and the ElementInternals interface, a custom element can take part in forms like a native control: submit a value, report validity, respond to a reset, be disabled by a fieldset and be reached by label. This post explains the pieces: static formAssociated, attachInternals, setFormValue, validation with setValidity, the form lifecycle callbacks, custom states with :state() and the accessibility links. The reference is the HTML Standard's form-associated custom elements section and the MDN page on [ElementInternals](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals). It is supported in all current browsers.

Opting in

Set static formAssociated = true on the class and call this.attachInternals() in the constructor. The returned ElementInternals object is the element's private link to the form system.

optin.jsJavaScript
class RatingInput extends HTMLElement {
  static formAssociated = true;

  #internals;
  #value = "";

  constructor() {
    super();
    this.#internals = this.attachInternals();
  }

  get form() {
    return this.#internals.form;
  }

  get name() {
    return this.getAttribute("name");
  }
}

customElements.define("rating-input", RatingInput);
Text
(rating-input elements inside a form are now associated with that form)

The element gets the form-related properties from the platform: form, name through the attribute, type and validity through the internals. The attribute name decides the key in the submitted data, just as for <input>.

Submitting a value

internals.setFormValue(value) sets what the control contributes to the form. The value can be a string, a File or a FormData. When the form is submitted or read with FormData, the entry appears under the element's name.

value.jsJavaScript
class RatingInput extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  connectedCallback() {
    this.tabIndex = 0;
    this.addEventListener("click", (event) => {
      const star = event.target.closest("[data-value]");
      if (star) this.value = star.dataset.value;
    });
    this.value = this.getAttribute("value") ?? "";
  }

  get value() {
    return this.getAttribute("value") ?? "";
  }

  set value(next) {
    this.setAttribute("value", next);
    this.#internals.setFormValue(next);
    this.textContent = "★".repeat(Number(next || 0));
  }
}

customElements.define("rating-input", RatingInput);
form.htmlHTML
<form id="review">
  <rating-input name="rating" value="4"></rating-input>
  <button>Send</button>
</form>
read.jsJavaScript
const data = new FormData(document.querySelector("#review"));
console.log(data.get("rating"));
Text
4

Call setFormValue whenever the value changes. Passing null removes the entry, which is how a control says "no value", like an unchecked checkbox. A second argument sets the "state", a value that the browser restores on form restoration, such as after navigating back, which can differ from what is submitted.

Validation

internals.setValidity(flags, message, anchor) marks the control invalid, with a message the browser shows on submit. The flags are the same as in the Constraint Validation API, such as valueMissing, tooShort and customError. Pass an empty object to mark it valid. The optional anchor is an element inside the component where the validation bubble points.

validity.jsJavaScript
class RatingInput extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  set value(next) {
    this.setAttribute("value", next);
    this.#internals.setFormValue(next);

    if (this.hasAttribute("required") && !next) {
      this.#internals.setValidity({ valueMissing: true }, "Please choose a rating.");
    } else {
      this.#internals.setValidity({});
    }
  }

  get validity() {
    return this.#internals.validity;
  }

  get validationMessage() {
    return this.#internals.validationMessage;
  }

  checkValidity() {
    return this.#internals.checkValidity();
  }
}
Text
(submit with no rating) the form does not submit, and the message "Please choose a rating." is shown

The element needs to expose validity, validationMessage, checkValidity() and reportValidity() itself, usually by delegating to the internals, as above, since the platform does not add them to a custom class. The form's own checkValidity() includes the element, and the CSS pseudo-classes :invalid and :valid apply to it. See the Constraint Validation API for the flags.

Form lifecycle callbacks

Form-associated elements get four extra callbacks.

CallbackCalled when
formAssociatedCallback(form)The element is associated with, or dissociated from, a form
formDisabledCallback(disabled)The element's disabled state changes, directly or through a fieldset
formResetCallback()The form is reset
formStateRestoreCallback(state, mode)The browser restores state, after navigation or autofill
callbacks.jsJavaScript
class RatingInput extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  formResetCallback() {
    this.value = this.getAttribute("value") ?? "";
  }

  formDisabledCallback(disabled) {
    this.toggleAttribute("aria-disabled", disabled);
    this.tabIndex = disabled ? -1 : 0;
  }

  formStateRestoreCallback(state) {
    this.value = state;
  }
}
Text
(form.reset()) the control returns to its initial value
(wrapped in <fieldset disabled>) the control stops accepting focus

For reset, the "default" value is whatever the value attribute says, as for a native input, so keep the attribute for the initial value and use a property for the current one. formStateRestoreCallback receives the second argument of setFormValue, and mode is "restore" or "autocomplete".

Custom states

The internals.states set, available in current browsers, lets a component expose states to CSS with the :state() pseudo-class, in the way native controls have :checked.

states.jsJavaScript
class ToggleButton extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  connectedCallback() {
    this.addEventListener("click", () => this.checked = !this.checked);
  }

  get checked() {
    return this.#internals.states.has("checked");
  }

  set checked(on) {
    if (on) {
      this.#internals.states.add("checked");
    } else {
      this.#internals.states.delete("checked");
    }
    this.#internals.setFormValue(on ? "on" : null);
  }
}

customElements.define("toggle-button", ToggleButton);
states.cssCSS
toggle-button:state(checked) {
  background: #16a34a;
  color: white;
}
Text
(click) toggle-button gets the :state(checked) style, and submits "on" when checked

Older Chromium versions used a --checked dashed ident syntax, and the standard settled on plain identifiers, so use the current form and check support. States are a clean replacement for classes and attributes that were visible to the page.

Accessibility with internals

ElementInternals also carries ARIA defaults, so the element has the right role without setting attributes on the host that the page could override. Set internals.role = "slider", internals.ariaValueNow = "4" and internals.ariaLabel in the constructor or when the value changes. Labels work: a <label for="id"> pointing to the element, or a wrapping label, is associated with it and available as internals.labels. Clicking the label focuses the element if it is focusable. Native semantics are still the best choice: if a native input or select does the job, use it, and use a custom control only when you need behavior the native ones lack. Also support the keyboard, with arrow keys for rating and sliders, and Space and Enter for toggles.

aria.jsJavaScript
constructor() {
  super();
  this.#internals = this.attachInternals();
  this.#internals.role = "slider";
  this.#internals.ariaValueMin = "1";
  this.#internals.ariaValueMax = "5";
}
Text
(a screen reader announces the element as a slider from 1 to 5)

Testing and fallbacks

Test the element inside a real <form>: set the value, build new FormData(form) and check the entry, then call form.reset() and check the default and call form.checkValidity() with and without the required rule. A browser test is best, since jsdom does not implement ElementInternals fully. Because the feature is in all current browsers, a fallback is rarely needed, and when it is, a hidden input appended in connectedCallback and kept in sync gives the same submission result. Detect support with "ElementInternals" in window && "setFormValue" in ElementInternals.prototype.

A complete small example

Putting the pieces together shows how little code a real control needs. A quantity stepper keeps its number in an attribute, reflects it to the form value, validates a range and responds to reset. The steps are always the same: store the value, call setFormValue, run the validation, and render. Putting these in one #sync() method that every change calls keeps the element consistent, and avoids the bug where the displayed value and the submitted value drift apart after a reset or a restore.

stepper.jsJavaScript
class QtyStepper extends HTMLElement {
  static formAssociated = true;
  static observedAttributes = ["value", "min", "max"];
  #internals = this.attachInternals();

  attributeChangedCallback() {
    this.#sync();
  }

  connectedCallback() {
    this.addEventListener("click", (event) => {
      const step = event.target.closest("[data-step]");
      if (step) this.setAttribute("value", String(this.value + Number(step.dataset.step)));
    });
    this.#sync();
  }

  get value() {
    return Number(this.getAttribute("value") ?? 0);
  }

  formResetCallback() {
    this.#sync();
  }

  #sync() {
    const min = Number(this.getAttribute("min") ?? 0);
    const max = Number(this.getAttribute("max") ?? 10);

    this.#internals.setFormValue(String(this.value));
    this.#internals.setValidity(
      this.value < min || this.value > max ? { rangeOverflow: true } : {},
      `Choose a number from ${min} to ${max}.`,
    );
  }
}

customElements.define("qty-stepper", QtyStepper);
Text
(value 3, min 1, max 5) FormData qty = "3", valid
(value 9) FormData qty = "9", invalid with the message "Choose a number from 1 to 5."

The message is stored only while the flags are set, so a valid state has no message. Because #sync() runs from the attribute callback, setting value from script, from a click or from the value attribute in HTML all give the same result.

Design advice

Treat the native controls as the specification. A text input, a checkbox and a select already define how value, validity, reset, disabled and focus should behave, and users expect your control to match: it must be reachable with Tab, operable with the keyboard, labelled by a <label>, announced with a role and a value, and respectful of disabled and required. Write down the list of those behaviors before building, and test each one by hand with the keyboard and a screen reader. A control that submits the right value but cannot be used without a mouse is not finished, and the platform features above remove the plumbing so that you can spend the time on this.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.