Goldfish Sandwich
Goldfish Sandwich

Reputation: 354

Why does the label element have a form attribute?

In the HTML standard, why does the HTML label element have a form attribute defined for it when it already has the for attribute? What purpose does it have?

If I have a label element where either the child contents are an input type or the for attribute is used what purpose does the form attribute have?

For example, in each of the label scenarios below the 'owning form' is known by either looking at the children or the parent elements. Is there another scenario where a label with a form attribute would be both useful and not increase clutter?

<body>
<form action="#" id="form-one" method="post">
    <label>Dog name<input type="text" id="tb-dog-name"></label>
    <button type="submit" id="form-one-submit">Post Dog Name</button>
</form>

<form action="#" id="form-two" method="post">
    <label for="tb-cat-name">Cat name</label>
    <input type="text" id="text-box-two">
    <button type="submit" id="form-two-submit">Post Cat Name</button>
</form>

<label for="tb-pizza">How much do you like pizza?</label>
<input type="text" id="tb-pizza" form="form-three">
<form action="#" id="form-three" method="post">
    <button type="submit" id="form-three-submit">Share your love!</button>
</form>

</body>

Upvotes: 3

Views: 104

Answers (1)

j08691
j08691

Reputation: 207901

As MDN states:

form (HTML5) The form element that the label element is associated with (its form owner). The value of the attribute must be an ID of a element in the same document. If this attribute is not specified, this element must be a descendant of a element. This attribute enables you to place label elements anywhere within a document, not just as descendants of their form elements.

Additionally: A form-associated element (button fieldset input keygen label object output select textarea img) is, by default, associated with its nearest ancestor form element (as described below), but, if it is reassociateable (button fieldset input keygen label object output select textarea), may have a form attribute specified to override this.

Upvotes: 1

Related Questions