12k
All articles

The HTML form Attribute Explained

See how the HTML form attribute connects outside controls to a form, and how ownership affects submission, validation, reset, JavaScript, React, and accessibility.

OpenReplay Team
OpenReplay Team
The HTML form Attribute Explained

The HTML form attribute links a form control to a <form> somewhere else on the page by matching that form’s id. From then on, the browser submits, validates and resets the control together with that form, the same way it would if the control were nested inside it.

Most developers find this out after they have already wrapped half a layout in one <form>, or written a click handler so a footer button can submit a form it isn’t inside.

This guide picks up from where the OpenReplay guide to native HTML validation attributes leaves off. That guide covers the attribute and the formaction-style overrides, which an outside submit button can still use. Here you get full patterns for sticky footers, editable tables and pages with several forms, plus how the attribute affects JavaScript APIs, the Enter key, validation, React and accessibility.

Key Takeaways

  • If the form attribute names an id that doesn’t belong to a <form>, the control has no form owner. It does not fall back to the <form> it is nested in.
  • A control has only one form owner, so a single input can’t be submitted with two forms.
  • form.elements, new FormData(form), constraint validation and form.reset() are all based on form ownership, not nesting.
  • Pressing Enter clicks the form’s default button. That is the first submit button in tree order that the form owns, and it can sit outside the <form> element.
  • Only listed elements accept form: button, fieldset, input, object, output, select, textarea and form-associated custom elements. <label> is not on that list.

Why Do Controls End Up Outside the Form?

Layout and form structure often disagree. A checkout page keeps “Place order” in a sticky footer. A modal puts Save in its header. An editable table needs one submission per row. The usual fixes have costs. A <form> around the whole page catches controls you didn’t mean to include. A click handler that calls requestSubmit() is extra wiring that every new layout needs again.

The WHATWG HTML spec’s section on associating controls with forms describes the form attribute as the answer to this, because HTML doesn’t allow forms to be nested. The value has to match the id of a <form> in the same tree as the control. If the first element in tree order with that id is not a <form>, the control gets no owner. Only listed elements take the attribute. A <label> has no form attribute. Its read-only label.form property only reports the form owner of the control it labels.

To attach a footer control to a form, give the form an id and point each outside control at it with form="id". That includes the submit button and any other field that has to live in the footer.

<main>
  <form id="checkout" method="post" action="/orders">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" required>

    <label for="card-name">Name on card</label>
    <input id="card-name" name="cardName" required>

    <label for="address">Shipping address</label>
    <textarea id="address" name="address" required></textarea>
  </form>
</main>

<footer class="sticky-footer">
  <label for="shipping">Shipping</label>
  <select id="shipping" name="shipping" form="checkout">
    <option value="standard">Standard</option>
    <option value="express">Express</option>
  </select>
  <button type="submit" form="checkout">Place order</button>
</footer>

No JavaScript is needed. The footer’s select is sent with the order, and the button gets native submission, validation and Enter-key handling. To confirm the wiring, run document.querySelector('footer button').form in the console. It returns the checkout form, or null if the id doesn’t match.

Modals need one adjustment. A form using method="dialog" closes its dialog only when the <form> element itself is inside the <dialog>. The submit button can still sit in the dialog header and point at the form by id.

Editable Tables: One Form per Row

A <form> can’t be a child of <table>, <tbody> or <tr>, so wrapping a form around each row produces invalid markup. When the parser repairs misplaced form tags, the resulting ownership is not what you wrote. A <td> accepts flow content, so you can put an empty form in one cell and point the row’s controls at it:

<table>
  <tr>
    <td><input name="name" value="Jane Doe" form="row-1" required></td>
    <td><input name="email" type="email" value="jane@example.com" form="row-1"></td>
    <td>
      <form id="row-1" method="post" action="/users/1"></form>
      <button type="submit" form="row-1">Save Jane Doe</button>
    </td>
  </tr>
  <tr>
    <td><input name="name" value="Sam Lee" form="row-2" required></td>
    <td><input name="email" type="email" value="sam@example.com" form="row-2"></td>
    <td>
      <form id="row-2" method="post" action="/users/2"></form>
      <button type="submit" form="row-2">Save Sam Lee</button>
    </td>
  </tr>
</table>

Each row now submits, validates and resets on its own. Radio button groups are also scoped by form owner, so radios with the same name in different rows don’t uncheck each other.

Two Forms on One Page

When a page has several forms, each outside control belongs to exactly one of them. This is the case on a settings screen with #profile and #notifications:

<form id="profile"><input name="displayName"></form>
<form id="notifications"><input type="checkbox" name="digest"></form>

<aside>
  <input name="bio" form="profile">
  <button type="submit" form="notifications">Save notifications</button>
</aside>

Three mistakes break form attribute wiring most often. An id typo leaves the control with no owner. An earlier non-form element with the same id also leaves it ownerless. A control nested inside one form but carrying form="other" belongs to other.

Setting form on a <fieldset> associates only the fieldset itself. Every input, select and button inside it still needs its own form attribute.

JavaScript: FormData, elements and reset()

A form’s JavaScript APIs pick up controls attached with the form attribute automatically. HTMLFormElement.elements is a live collection, in tree order, of every listed control the form owns, except input type="image". The spec builds the entry list for submission and the set of controls to reset from form ownership too.

const form = document.getElementById('checkout');

console.log([...form.elements].includes(document.getElementById('shipping'))); // true
console.log([...new FormData(form).keys()]); // includes "shipping" from the footer
form.reset(); // the footer <select> returns to its default too

form.addEventListener('submit', (e) => {
  e.preventDefault();
  console.log(e.submitter); // the footer <button>
  const data = new FormData(form, e.submitter); // adds the button's name/value if it has one
});

Entries come out in tree order. An outside control placed before the <form> in the DOM therefore appears first. A submit button adds data only when it is the submitter, which is why the FormData constructor takes an optional submitter argument. SubmitEvent.submitter points at the outside button. One caution: an outside control named action or submit shadows that property on the form, just as a nested control would.

How Does the form Attribute Affect the Enter Key and Validation?

According to the spec’s implicit submission rules, pressing Enter in a text field clicks the form’s default button. That button is the first submit button in tree order owned by the form. In the checkout example, Enter in the email field triggers the footer’s “Place order” button. If you place a form="checkout" button in a header before the form in the DOM, that header button becomes the default instead of any button inside the form. When a form owns no submit button, Enter submits only if the form has at most one field that blocks implicit submission. Outside fields count toward that limit.

Interactive constraint validation covers every submittable control the form owns. A required field in the footer blocks submission like any other. After a submit attempt, outside fields get :user-invalid too, so the patterns in styling valid and invalid form states with CSS work on them unchanged.

React and Other Frameworks

React lists form as a supported prop on <input> and <select>. In both cases it takes the id of the form the element belongs to. If you leave it out, the element belongs to its closest parent form. Because browsers dispatch the submit event at the form, not at the button, the form’s onSubmit handler still runs when the button sits outside it. Controlled inputs keep their value/onChange behaviour.

import { useState } from 'react';

function Checkout() {
  const [email, setEmail] = useState('');
  return (
    <>
      <form id="checkout" onSubmit={(e) => { e.preventDefault(); /* send */ }}>
        <input name="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      </form>
      <footer><button type="submit" form="checkout">Place order</button></footer>
    </>
  );
}

Form ownership follows the real DOM, not the component tree. A button rendered through createPortal leaves the form’s subtree, so it needs form to stay connected. Vue, Svelte and other frameworks render form as a plain HTML attribute.

Accessibility of Detached Controls

For controls attached with the form attribute, tab order and reading order follow DOM order, not form ownership. Place detached controls where their DOM position makes sense, for example a footer after the main content. A screen reader user can reach the button far from the fields, so its text should name the action (“Place order”, not “Submit”). In tables, give each row’s button a distinct name, such as “Save Jane Doe”, using visible text or aria-label.

Conclusion

Form ownership, not nesting, decides which controls a form submits, validates and resets. Use form="id" instead of extra wrappers or click handlers. Check the wiring with control.form and keep DOM order logical for keyboard users. A good first target is any button in your codebase that calls requestSubmit() from outside a form. Replace it with a native submit button that carries form.

FAQs

What is the difference between the form attribute and formaction?

The form attribute decides which form owns a control. The formaction, formmethod, formenctype, formnovalidate and formtarget attributes change how the owning form submits, and they apply only when that specific submit button triggers the submission. The two combine: a footer button with form='checkout' and formaction='/orders/draft' submits the checkout form's data to the draft URL instead of the form's own action.

Can I change which form a control belongs to with JavaScript?

Yes. Call setAttribute('form', 'profile') or removeAttribute('form') on the control. The browser recalculates the form owner whenever the form attribute is set, changed or removed, and also when an id in the tree changes. The form property, as in input.form, is read-only. Assigning a value to it does not change ownership, so always change the attribute instead.

Does a control attached with the form attribute inherit the form's autocomplete setting?

Yes. A control with no autocomplete attribute of its own uses the autocomplete state of its form owner, so autocomplete='off' on the form also applies to footer fields attached with form='checkout'. If the form attribute matches no form, the control has no owner and defaults to 'on'. Give the control its own autocomplete value to override the form's setting.

Does a disabled fieldset disable controls attached to it with the form attribute?

No. A disabled fieldset disables only the controls nested inside it in the DOM, apart from content inside its first legend. A control placed elsewhere that points at the same form with the form attribute stays enabled. A control nested inside a disabled fieldset is disabled even if its form attribute names another form. Disabled controls are left out of both submission and constraint validation.

Open-source session replay

Complete picture for complete understanding

Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.