One challenge that developers have faced when creating HTML5 forms is the inability to separate a form control from its parent
<form> element without having to resort to some undesirable methods to get that form control to submit its data along with the form.
If you tried to do this in HTML4 or XHTML, the form would not submit the information from the form control that’s structurally outside the form.
A Better Way to Associate Form Controls
HTML5 now introduces a new
form attribute that allows you to associate any orphaned form control with any
<form> element on the page. You can read up on this technique on the WHATWG HTML5 spec in the section Association of Controls and Forms, but here’s how this is done:
<form id="contact_form" method="get"> <label>Name:</label> <input type="text" id="name" name="name"> <label>Email:</label> <input type="email" id="email" name="email"> <input type="submit" id="submit" value="SEND"> </form> <textarea id="comments" form="contact_form"></textarea>
Notice two things:
<textarea>element is outside the
<form>element (i.e. it’s a sibling, not a child)
<textarea>element has a
formattribute with a value that’s equal to the
idof the form with which I want it to be associated
HTML5 form Attribute Overrides Default Behaviour
With this attribute, you can actually override the default form control association behaviour. For example, if there are two forms on a page, you can “steal” a form control from form #2 and make it submit along with form #1.
This would happen even if the form control is nested inside of form element #2. And as a result, form #2 would not submit the “stolen” form control’s data. So the
form attribute will override what would naturally happen.
formattribute and it will work the same way. Thanks to Veera for asking about that.
This feature is currently supported in all browsers except for Internet Explorer (not even IE11). So as long as you don’t have to support those older browsers, you should be fine to use this in any project.
I’ve set up a demo page with a form that has its
method attribute set to “get” and that uses the HTML5
form attribute. This will cause the submitted values to be sent to the same page in a query string. If you’re using a browser that supports this feature, then you should see three values appended to the URL. If you’re using a nonsupporting browser, then you’ll see only two values.