input type="text"
input type="checkbox"
input type="radio"
input type="password"
input type="hidden"
— for data the user cannot viewinput type="file"
— for uploadstextarea
— for longer text entryselect
— for drop-down listsbutton
— generally used for submitting a form, althoughinput type="submit"
andinput type="image"
could also be used.
Also:
- CSS styling possibilities were limited,
- custom controls such as date and color pickers had to be developed in code, and
- client-side validation required JavaScript.
Additional HTML5 Input Types
A deluge of newinput
types have been introduced. These provide native input assistance and validation without any JavaScript code…
type | description |
---|---|
email |
enter an email address |
tel |
enter a telephone number — no strict syntax is enforced but line breaks will be removed |
url |
enter a URL |
search |
a search field with line breaks automatically removed |
number |
a floating point number |
range |
a control for entering an approximate value, typically represented by a slider |
date |
enter the day, month and year |
datetime |
enter the day, month, year, hour, minute, second and microsecond based on the current UTC timezone |
datetime-local |
enter a date and time with no timezone |
month |
enter the month and year with no timezone |
week |
enter a week number with no timezone |
time |
enter the time with no timezone |
color |
specify a color |
Input Attributes
Unless stated otherwise, input fields can have any of the following form-specific attributes. Several are Boolean attributes, that is, they do not require values, e.g<input type="email" name="email" required />
although you can add them if you prefer a stricter XHTML-like syntax, e.g.
<input type="email" name="email" required="required" />
attribute | description |
---|---|
name |
the input field name |
value |
an initial value |
checked |
checks a checkbox or radio input |
maxlength |
the maximum length of the entered string. This can also be applied to textarea fields in HTML5 |
minlength |
the minimum length of the entered string. This is documented but, at the time of writing, browser support is poor and the attribute causes HTML validators to error. An alternative option is pattern=".{3,}" which would enforce at least three characters. |
placeholder |
a subtle text hint shown in the input box |
autofocus |
set focus to this (non-hidden) field when the page loads |
required |
indicates that a value must be entered |
pattern |
ensures a value adheres to a regular expression |
min |
the minimum value permitted (numeric and date types) |
max |
the maximum value permitted (numeric and date types) |
step |
the value granularity. For example, input type="number" min="10" max="19" step="2" would only permit the values 10, 12, 14, 16 or 18. |
autocomplete |
provides the browser with a hint for auto-completion, e.g. “billing email” or can be set to “on” or “off” to enable and disable accordingly |
inputmode |
specifies the input mechanism. The most useful options:
|
size |
the size in characters for text or password inputs or pixels for email , tel , url or search inputs. Probably best avoided since you should use CSS to style fields. |
rows |
number of text rows (textarea only) |
cols |
number of text columns (textarea only) |
list |
points to a set datalist options |
spellcheck |
set to true or false to enable or disable spell checking |
form |
the ID of the form which this input belongs to. In general, inputs should be nested inside a form , but this attribute permits an input to be defined anywhere on the page |
formaction |
specifies a URI to override the form action when submitting (submit buttons/images only) |
formmethod |
specifies GET or POST to override the form method when submitting (submit buttons/images only) |
formenctype |
specifies the type of content when submitting (text/plain , multipart/form-data or application/x-www-form-urlencoded on submit buttons/images only) |
formtarget |
specifies a target window/frame to override the form target when submitting (submit buttons/images only) |
readonly |
the input value cannot be changed although it will be validated and submitted |
disabled |
disables the input — no validation will occur and data will not be submitted |
Note that
date
fields must always use YYYY-MM-DD for value
, min
and max
attributes.
The following example requests a mandatory email which ends in @mysite.com and has focus when the page loads:
<input
type="email"
name="login"
pattern="@mysite\.com$"
autocomplete="email"
autofocus
required />
Datalists
A datalist contains a set of suitable options for any type ofinput
, e.g.
<input type="text" name="browser" list="browsers" />
<datalist id="browsers">
<option value="Chrome" />
<option value="Firefox" />
<option value="Internet Explorer" />
<option value="Safari" />
<option value="Opera" />
</datalist>
When
datalist
is supported, the browser presents auto-complete options when you start to type. The whole list is usually shown if you double-click the control or click the down arrow (if shown). Unlike a standard select
drop-down, the user is free to override these choices and enter their own value.
It’s possible to set values and text like standard select options, e.g.
<option value="IE">Internet Explorer</option>
but be aware that implementations differ. For example, Firefox auto-completes on the text itself (Internet Explorer) while Chrome prefers the value (IE) and shows the text greyed out:
Datalists can be populated by JavaScript if you wanted to retrieve options via Ajax.
Disabling Validation
Validation for the whole form can be disabled by setting anovalidate
attribute on the form
element. Alternatively, you can set a formnovalidate
attribute on the form’s submit button/image.
Remember also that setting an input’s disabled
attribute will prevent validation on that field.
Output Fields
While we’re primarily discussing input types, HTML5 also provides read-only output options:output
— the result of a calculation or user actionprogress
— a progress bar (thevalue
andmax
attributes define the status)meter
— a scale which can change between green, amber and red depending on the values set for the attributesvalue
,min
,max
,low
,high
andoptimum
Separating and Labeling Inputs
The whatwg.org form specification states:Each part of a form is considered a paragraph, and is typically separated from other parts using <p> elementsInteresting. I normally use a
div
although I doubt it matters from a semantic perspective. A p
tag is shorter although it’s possible you’ll need to apply a class to modify margins.
More importantly, you should use label elements either around or next to the input itself with a for
attribute stating the input’s ID, e.g.
<p>
<p>
<label for="firstname">First name</label>
<input type="text" id="firstname" name="firstname" placeholder="first name" required maxlength="20" />
</p>
<p>
<label for="lastname">Last name</label>
<input type="text" id="lastname" name="lastname" placeholder="last name" required maxlength="20" />
</p>
<p>
<label for="email">Email address</label>
<input type="email" id="email" name="email" placeholder="your@email.address" required maxlength="50" />
</p>
<p>
<label>
<input type="checkbox" name="newsletter" />
Sign up for our newsletter
</label>
</p>
No Standard Controls
There are no specific interface guidelines for browser vendors to follow. This is intentional: a typical desktop mouse-controlled date picker can be too small on a mobile device so the vendor can implement a touch-based alternative.Browser Support
Not every input type and attribute is supported in all browsers. In general, most modern browsers from IE10+ include basics such as email and number. However, the date types are only supported in Webkit and Blink browsers at the time of writing. The browser will revert to a standardtext
input when a specific type and ignore attributes when those values are not supported.
Always Use the Correct Type!
It’s important to use the correct input type for the data you’re requesting. That may seem obvious but you will encounter situations when you’ll be tempted to use a standard text input. Consider dates. Support is patchy and this leads to implementation issues:- The standard
date
input always returns dates in YYYY-MM-DD format regardless of how the date picker is presented in your locale. - IE and Firefox will fall back to a standard
text
input, but your users may expect to enter values in US MM-DD-YYYY or European DD-MM-YYYY format. - A JavaScript date picker such as the one in jQuery UI allows you to define a custom format — or even YYYY-MM-DD for consistency — but you cannot guarantee JavaScript will be enabled.
date
input, revert to text
and implement your own date control. Don’t. You will never create a custom date picker which works in all devices at all screen resolutions, supports keyboard, mouse and touch input and continues to operate when JavaScript is disabled. In particular, mobile browsers are often ahead of their desktop cousins and implement good touch-screen controls.
The HTML5 input types are the future. Use them and, if necessary, add JavaScript polyfills in situations where you require good cross-browser support. But remember to…
Validate Server-Side
Browser validation is not guaranteed. Even if you forced everyone to access using the latest version of Chrome you could never prevent:- browser bugs or JavaScript failures permitting invalid data
- the user changing your HTML or scripts using browser tools
- submission from systems outside your control, or
- data interception between the browser and the server (certainly over HTTP).
Frequently Asked Questions (FAQs) about HTML5 Forms Markup
What is the importance of using HTML5 in form markup?
HTML5 introduces a range of new input types and attributes that provide a better user experience for form filling. These new features allow for more specific input types, such as email, date, and time, which can be validated by the browser itself, reducing the need for additional JavaScript. This leads to cleaner, more efficient code and a smoother user experience.
How does HTML5 improve accessibility in form markup?
HTML5 provides several features that enhance accessibility. For instance, the “required” attribute can be used to ensure that essential fields are filled in. The “placeholder” attribute can provide hints to users about what type of information is expected in a field. Additionally, the “autofocus” attribute can automatically focus the cursor on a particular input field when the page loads, guiding the user’s interaction with the form.
What are some common mistakes to avoid when using HTML5 for form markup?
One common mistake is not properly using the new input types and attributes introduced in HTML5. For example, using the wrong input type can lead to incorrect data being submitted. Another mistake is not providing adequate fallbacks for older browsers that do not support HTML5. This can lead to a poor user experience for those using older technology.
How can I use HTML5 to create more interactive forms?
HTML5 introduces several new form elements that can be used to create more interactive forms. For example, the “datalist” element can be used to create a dropdown list of options for an input field, while the “progress” and “meter” elements can be used to visually represent the progress of a task or the current value within a known range, respectively.
How does HTML5 handle form validation?
HTML5 introduces built-in form validation through the use of certain attributes. For example, the “required” attribute can be used to ensure that a field is not left empty, while the “pattern” attribute can be used to specify a regular expression that the input field’s value must match. If the input does not meet these criteria, the form will not be submitted and the user will be prompted to correct their input.
What are the benefits of using semantic elements in HTML5?
Semantic elements in HTML5 provide a clear indication of what type of content is contained within them, making it easier for both developers and machines (like search engines) to understand the structure and content of a webpage. This can improve search engine optimization and accessibility.
How can I ensure my HTML5 forms are compatible with older browsers?
While HTML5 is widely supported by modern browsers, it’s important to provide fallbacks for older browsers that may not support all HTML5 features. This can be done by using JavaScript to detect whether a browser supports a particular feature and providing an alternative implementation if it does not.
How can I use HTML5 to improve the mobile experience of my forms?
HTML5 introduces several features that can improve the mobile experience of forms. For example, the “autofocus” attribute can be used to automatically focus the cursor on a particular input field when the page loads, reducing the need for users to manually tap the field. Additionally, the new input types like “email” and “tel” bring up specialized keyboards on mobile devices, making it easier for users to input the correct type of data.
What are some best practices for structuring a web form in HTML5?
Some best practices for structuring a web form in HTML5 include grouping related form controls using the “fieldset” element, providing descriptive labels for all form controls using the “label” element, and using the “legend” element to provide a caption for each “fieldset”. Additionally, it’s important to use the appropriate input types and attributes to ensure data validity and improve user experience.
How can I use CSS to style my HTML5 forms?
CSS can be used to style HTML5 forms in a variety of ways. For example, you can use CSS to change the color, size, and font of form elements, add borders and backgrounds, and apply hover effects. Additionally, CSS can be used to control the layout of form elements, such as aligning form controls and labels, and creating multi-column forms.
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.