The HTML5 form Attribute

Share this article

HTML4 and XHTML insisted that all form elements — including the submit button — were contained within a single <form>…</form> block. While this is rarely an issue, it can lead to design challenges and I certainly recall struggling with early versions of ASP.NET which enforced a single form on every page. In general, if you required an input field outside the form, you’d need JavaScript to import its value when the form was submitted.

One of the lesser-known HTML5 features is the form attribute. It allows you to reference a specific form by its ID on any orphaned field, e.g.

<form id="myform1" method="post">
 <label for="name">name:</label>
 <input type="text" name="name" />

 <label for="email">email:</label>
 <input type="email" name="email" /></form>

<input type="number" form="myform1" name="age" />

<button form="myform1" type="submit">Submit</button>

Interestingly, the form attribute allows you to place a field in one form that is submitted in another. Alternatively, you could change form attributes in JavaScript rather than importing values, e.g.

<script type="text/javascript">// <![CDATA[
// grab fieldx from another form
document.getElementById("myform1").addEventListener("submit", function(e) {

	document.getElementById("fieldx").setAttribute("form", e.target.id);
	return true;

}, false);
// ]]></script>

Browser Support

The form attribute is supported in all browsers — except any version of Internet Explorer. For that reason alone, it’s probably not worth using unless your orphaned fields are relatively unimportant and you’re happy to lose data.

But does this feel right? Perhaps it’s because I’ve been writing self-contained forms for many years, but I wouldn’t suggest using the form attribute unless there was no other option. At best, it’s a little inelegant. At worst, it’ll confuse you and your colleagues when you examine the code in a few months time. But it’s reassuring to know it’s there should you need it!

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

FormsHTML5 Dev CenterHTML5 Tutorials & Articles
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week