HTML5 Forms: New Controls

Share this article

HTML5 Forms: New Controls

htmlcss2thumb

The following is an extract from our book, HTML5 & CSS3 for the Real World, 2nd Edition, written by Alexis Goldstein, Louis Lazaris, and Estelle Weyl. Copies are sold in stores worldwide, or you can buy it in ebook form here.

We’ve covered the new values for the input element’s type attribute, along with some attributes that are valid on most form elements. But HTML5 web forms still have more to offer us! There are five new form elements in the HTML5 forms specification: datalist, output, keygen, progress, and meter. We covered datalist above. We introduced you to progress and meter in the last chapter as they are often useful outside of forms. So let’s recap and take a look at the other two elements.

The progress and meter Elements

Two of the most well-known HTML5 elements are the progress and meter elements.

The meter element provides for a gauge, displaying a general value within a range. You provide minimum (min) and maximum (max) values, and the required value that falls between those minimum and maximum values. While many think it’s a form control with attributes similar to some numeric input types, it has no name attribute and won’t be submitted on form submission.

The meter will default the minimum value to 0, or the meter’s value, whichever is lower. The maximum value defaults to 1 or the meter’s value, whichever is higher. Use meter when there is a minimum value, a maximum value, and optimal values, and the value can go up and down like a test grade, gas tank level, or blood pressure. With these three attributes, browsers that support meter including Android 4.4+ (but not iOS7 or IE11) will show a green gauge.

meter enables us to show when a value is in the right range with the low, high, and optimum values. If the value is between min and low, the meter is yellow. If the value is between the low and high value the meter is green. If the value is between high and max, it will be red. Currently the optimum value has no noticeable effect.

The meter element should not be used to indicate progress; instead, use a progress bar to indicate the percentage of how complete a task is.

Progress attributes include max and value, with progress always being between 0 and 100% complete. The browser calculates what percentage the value is of the maximum and adjusts the length of the progress bar accordingly. It displays a partially filled gray to blue progress bar where it is fully gray at 0% and fully blue at 100%.

If no value is included, the progress bar is indeterminate. Chrome, Opera, Safari, and Firefox display indeterminate progress as animated bars, with IE styling it as animated dots.

Unlike meter, progress heads only in the direction of 100% of the max value. The presentation defaults to inline-block so you can set width and height on progress elements. Height will not change the actual height of the stylized bar (unlike meter) but will add space below it.

The output Element

The purpose of the output element is to accept and display the result of a calculation. The output element should be used when the user can see the value, but not directly manipulate it, and when the value can be derived from other values entered in the form. An example use might be the total cost calculated after shipping and taxes in a shopping cart.

The output element’s value is contained between the opening and closing tags. Generally, it will make sense to use JavaScript in the browser to update this value. The output element has a for attribute, which is used to reference the IDs of form fields whose values went into the calculation of the output element’s value.

The output element’s name and value are submitted along with the form.

The keygen element is a control for generating a public-private key pair and for submitting the public key from that key pair. Opera, Chrome, Safari, Android, and Firefox all support this element, rendering it as a drop-down menu with options for the length of the generated keys; all provide different options, though. There is still no support in iOS7 and IE11.

The keygen element introduces two new attributes: the challenge attribute specifies a string that is submitted along with the public key, and the keytype attribute specifies the type of key generated. At the time of writing, the only supported keytype value is rsa, a common algorithm used in public-key cryptography.

The contenteditable Attribute

While it is always best to use the most appropriate form element for its intended purpose, sometimes the existing form elements fall short of our needs; for example, no form control makes for a good inline WYSIWYG text editor.

There is a roundabout solution for that, though. Any element in an HTML5 document can be made editable with the contenteditable attribute. The contenteditable attribute, written simply as contenteditable or contenteditable="true", makes the element on which it is included editable. You will usually find this attribute on divs, but you can even make a style element that’s set to "display:block" editable, and change CSS on the fly. While any element that is not natively a form control will not by default be sent to the server with the rest of the form data on form submission, you can use JavaScript to send user edited content to the server asynchronously or on form submission.

If you’ve ever seen an editable profile where the element to click doesn’t look like a form control at all, there is a chance that you were actually editing a contenteditable element. Any edits made on contenteditable components actually update the DOM.

Simply adding contenteditable to an element makes that element editable in all browsers. In addition, its descendents will also be editable unless contenteditable="false" is explicitly applied to them. While this does update the DOM client side, you do have to add JavaScript to explicitly save it.

Changes to Existing Form Controls

There have been a few other changes to form controls in HTML5.

The form Element

Throughout this chapter, we’ve been talking about attributes that apply to various form field elements; however, there are also some new attributes specific to the form element itself.

First, as we’ve seen, HTML5 provides a number of ways to natively validate form fields; certain input types such as email and url, for example, as well as the required and pattern attributes. You may, however, want to use these input types and attributes for styling or semantic reasons without preventing the form being submitted. The new Boolean novalidate attribute allows a form to be submitted without native validation of its fields.

Next, forms no longer need to have the action attribute defined. You no longer need to explicitly state the URL to use it for form submission. If omitted, the form will behave as though the action were set to the current page. You can write or override the URL defined in the form’s action attribute with the formaction attribute of the button input types that activate form submission.

Lastly, the autocomplete attribute we introduced earlier can also be added directly to the form element; in this case, it will apply to all fields in that form unless those fields override it with their own autocomplete attribute.

The optgroup Element

In HTML5, you can have an optgroup as a child of another optgroup, which is useful for multilevel select menus.

The textarea Element

In HTML 4, we were required to specify a textarea element’s size by specifying values for the rows and cols attributes. In HTML5, these attributes are no longer required; you should use CSS to define a textarea’s width and height.

New in HTML5 is the wrap attribute. This attribute applies to the textarea element, and can have the values soft (the default) or hard. With soft, the text is submitted without line breaks other than those actually entered by the user, whereas hard will submit any line breaks introduced by the browser due to the size of the field. If you set the wrap to hard, you need to specify a cols attribute.

In Conclusion

Unfortunately, we weren’t able to cover everything—that should be a book in itself. This was, however, a fairly in-depth introduction. As support for HTML5 input elements and attributes grows, sites will require less and less JavaScript for client-side validation and user interface enhancements, while browsers handle most of the heavy lifting. Legacy user agents are likely to stick around for the foreseeable future, but there is no reason to avoid moving forward and using HTML5 web forms, with appropriate polyfills and fallbacks filling the gaps where required.

In the next chapter, we’ll continue fleshing out The HTML5 Herald by adding what many consider to be HTML5’s killer feature: native video and audio.

Frequently Asked Questions (FAQs) about HTML5 Forms and New Controls

What are the new form elements introduced in HTML5?

HTML5 introduced several new form elements to enhance user experience and provide better data collection. These include ‘datalist’, which provides an autocomplete feature; ‘output’, which displays the result of a calculation; ‘keygen’, which facilitates secure form submission; ‘progress’, which displays the progress of a task; and ‘meter’, which measures data within a given range.

How does the ‘datalist’ element in HTML5 work?

The ‘datalist’ element in HTML5 provides an autocomplete feature for input fields. It works in conjunction with the ‘input’ element and the ‘list’ attribute. The ‘datalist’ element contains a set of ‘option’ elements that represent the available options for the input field. As the user types in the input field, the browser displays matching options from the datalist.

How can I use the ‘output’ element in HTML5?

The ‘output’ element in HTML5 is used to display the result of a calculation. It works in conjunction with the ‘oninput’ event attribute. When the user inputs data, the ‘oninput’ event triggers a JavaScript function that performs a calculation and displays the result in the ‘output’ element.

What is the purpose of the ‘keygen’ element in HTML5?

The ‘keygen’ element in HTML5 is used to facilitate secure form submission. It generates a pair of cryptographic keys – a public key and a private key. The public key is sent with the form data when the form is submitted, while the private key is stored locally on the user’s device. This allows the server to authenticate the user and ensure the integrity of the form data.

How does the ‘progress’ element in HTML5 work?

The ‘progress’ element in HTML5 is used to display the progress of a task. It has two attributes: ‘value’ and ‘max’. The ‘value’ attribute represents the current progress, while the ‘max’ attribute represents the total progress. The browser calculates the percentage of progress and displays it as a progress bar.

What is the ‘meter’ element in HTML5 used for?

The ‘meter’ element in HTML5 is used to measure data within a given range. It has three attributes: ‘value’, ‘min’, and ‘max’. The ‘value’ attribute represents the current value, while the ‘min’ and ‘max’ attributes represent the minimum and maximum values of the range. The browser displays the value as a gauge, with the gauge filled up to the proportion of the value within the range.

How can I style HTML5 form elements?

HTML5 form elements can be styled using CSS. You can apply styles to the elements directly, or you can use pseudo-classes to style specific states of the elements. For example, you can use the ‘:focus’ pseudo-class to style an input field when it has focus, or the ‘:valid’ and ‘:invalid’ pseudo-classes to style valid and invalid input.

How can I validate HTML5 form data?

HTML5 provides built-in form validation through the use of attributes such as ‘required’, ‘pattern’, and ‘type’. The ‘required’ attribute specifies that an input field must be filled out. The ‘pattern’ attribute specifies a regular expression that the input data must match. The ‘type’ attribute specifies the type of data that the input field should accept, such as ’email’, ‘number’, or ‘date’.

How can I handle HTML5 form events?

HTML5 form events can be handled using JavaScript. You can use the ‘addEventListener’ method to attach event handlers to form elements. The event handlers can perform actions such as validating input data, performing calculations, or submitting the form.

How can I use HTML5 forms for mobile devices?

HTML5 forms are designed to be responsive and work well on mobile devices. You can use the ‘viewport’ meta tag to control the layout on different screen sizes. You can also use the ‘type’ attribute of the ‘input’ element to specify input types that are optimized for mobile devices, such as ‘tel’, ’email’, and ‘date’.

Alexis GoldsteinAlexis Goldstein
View Author

Alexis Goldstein first taught herself HTML while a high school student in the mid-1990s, and went on to get her degree in Computer Science from Columbia University. She runs her own software development and training company, aut faciam LLC. Before striking out on her own, Alexis spent seven years in Technology on Wall Street, where she worked in both the cash equity and equity derivative spaces at three major firms, and learned to love daily code reviews. She is a teacher and a co-organizer of Girl Develop It, and a very proud member of the NYC Resistor hackerspace in Brooklyn, NY.

Louis LazarisLouis Lazaris
View Author

Louis is a front-end developer, writer, and author who has been involved in the web dev industry since 2000. He blogs at Impressive Webs and curates Web Tools Weekly, a newsletter for front-end developers with a focus on tools.

Estelle WeylEstelle Weyl
View Author

Estelle Weyl is a front-end engineer from San Francisco who has been developing standards-based accessible websites since 1999. She also writes two technical blogs with millions of visitors. Her passion is teaching web development so you'll find her speaking about CSS3, HTML5, JavaScript, and mobile web development at conferences around the United States.

book excerptFormsHTML5 Tutorials & Articles
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form