HTML form Attribute

Description

The HTML form attribute is used to associate an input or other form element with a form elsewhere in the document, rather than placing the element inside the <form> element itself. This attribute can prove particularly useful when you need to position form elements in different locations within the page layout, yet still want them to be submitted as part of a single form.

The form attribute contains the ID of the form it is associated with. When the form is submitted, the input element with the form attribute will be included in the submission, just as if it were inside the form element.

Here's a brief overview of its functionality:

  • Attribute Name: form
  • Applicable Elements: Input elements like <input>, <button>, <select>, <textarea>, and <fieldset> can use the form attribute.
  • Value: The value of the form attribute must be the ID of a <form> element that exists within the HTML document.
  • Purpose: To associate the element with a form elsewhere in the document, which allows for a more flexible layout while ensuring the form behaves as intended.

For example, if you have a form with the ID "loginForm" and you want to associate an input element with this form, but the input element is not a child of the <form> element due to layout constraints, you can use the form attribute like so:

<form id="loginForm" action="/submit" method="post">
  <!-- other form elements here -->
</form>
<input type="text" name="username" form="loginForm">

In this example, the <input> element for the username is not a child of the <form> element. However, by using the form attribute with a value that matches the ID of the form, the username input will still be submitted with the "loginForm" form.

Syntax

<tagname form="form-id">

Values

  • form-idThe id value of the form.

Applies To

The form attribute can be used on the following html elements.

Example

<form id="myForm" action="formscript.php" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>

<!-- This input is visually separated from the form above but is still associated with it -->
<input type="email" id="email" name="email" form="myForm" placeholder="Enter your email">

Browser Support

The following table will show you the current browser support for the HTML form Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 29th March 2024