December 5, 2014 in HTML5

The HTML5 form Attribute

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.

1
2
3
4
5
6
7
8
9
10
<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.

1
2
3
4
5
6
7
8
9
<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!

Source Link: http://www.sitepoint.com/the-html5-form-attribute/




By browsing this website, you agree to our privacy policy.
I Agree