HTML5′s New “form” Attribute.
By Louis Lazaris on June 14th, 2011
Categories: HTML5, Web Design Tutorials |
One challenge that developers have faced when creating 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
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”>
- <input type=“text” id=“name” name=“name”>
- <input type=“email” id=“email” name=“email”>
- <input type=“submit” id=“submit” value=“SEND”>
- <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
form attribute with a value that’s equal to the
id of the form with which I want it to be associated
It Overrides the 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.
I’ve set up a demo page with a form that has its
method attribute set to “get”. 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.
I couldn’t find too many sources that discuss browser support for this feature, but according tothis page and the sidebar column in the WHATWG spec, browser support is as follows:
- Opera 9.5+ (full support)
- Safari 5.1+ (according to Elliot; not sure of level of support)
- Firefox 4+ (buggy or partial support)
- Chrome 10+ (buggy or partial support)
- IE (no support)
From my own testing, I got pretty much the same results as described above, except I can’t confirm partial or buggy support; as far as I could tell, it works the same in FF, Opera, and Chrome. You can go ahead and try it in your browser of choice to confirm or correct anything written here.