4.10. Forms
4.10.1. Introduction
This section is non-normative.
A form is a component of a Web page that has form controls, such as text fields, buttons, checkboxes, range controls, or color pickers. A user can interact with such a form, providing data that can then be sent to the server for further processing (e.g., returning the results of a search or calculation). No client-side scripting is needed in many cases, though an API is available so that scripts can augment the user experience or use forms for purposes other than submitting data to a server.
Writing a form consists of several steps, which can be performed in any order: writing the user interface, implementing the server-side processing, and configuring the user interface to communicate with the server.
4.10.1.1. Writing a form’s user interface
This section is non-normative.
For the purposes of this brief introduction, we will create a pizza ordering form.
Any form starts with a form
element, inside which are placed the controls. Most
controls are represented by the input
element, which by default provides a one-line
text field. To label a control, the label
element is used; the label text and the
control itself go inside the label
element. Each area within a form is typically represented
using a div
element. Putting this together, here is how one might ask for the customer’s name:
<form> <div><label>Customer name: <input></label></div> </form>
To let the user select the size of the pizza, we can use a set of radio buttons. Radio buttons
also use the input
element, this time with a type
attribute with the value radio
. To make the radio buttons work as a group, they are
given a common name using the name
attribute. To group a batch
of controls together, such as, in this case, the radio buttons, one can use the fieldset
element. The title of such a group of controls is given by the first element
in the fieldset
, which has to be a legend
element.
<form> <div><label>Customer name: <input></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size> Small </label></div> <div><label> <input type=radio name=size> Medium </label></div> <div><label> <input type=radio name=size> Large </label></div> </fieldset> </form>
Changes from the previous step are highlighted.
To pick toppings, we can use checkboxes. These use the input
element with a type
attribute with the value checkbox
:
<form> <div><label>Customer name: <input></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size> Small </label></div> <div><label> <input type=radio name=size> Medium </label></div> <div><label> <input type=radio name=size> Large </label></div> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <div><label> <input type=checkbox> Bacon </label></div> <div><label> <input type=checkbox> Extra Cheese </label></div> <div><label> <input type=checkbox> Onion </label></div> <div><label> <input type=checkbox> Mushroom </label></div> </fieldset> </form>
The pizzeria for which this form is being written is always making mistakes, so it needs a way
to contact the customer. For this purpose, we can use form controls specifically for telephone
numbers (input
elements with their type
attribute set to tel
) and e-mail addresses
(input
elements with their type
attribute set to email
):
<form> <div><label>Customer name: <input></label></div> <div><label>Telephone: <input type=tel></label></div> <div><label>E-mail address: <input type=email></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size> Small </label></div> <div><label> <input type=radio name=size> Medium </label></div> <div><label> <input type=radio name=size> Large </label></div> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <div><label> <input type=checkbox> Bacon </label></div> <div><label> <input type=checkbox> Extra Cheese </label></div> <div><label> <input type=checkbox> Onion </label></div> <div><label> <input type=checkbox> Mushroom </label></div> </fieldset> </form>
We can use an input
element with its type
attribute set to time
to ask for a delivery time. Many
of these form controls have attributes to control exactly what values can be specified; in this
case, three attributes of particular interest are min
, max
, and step
. These set the
minimum time, the maximum time, and the interval between allowed values (in seconds). This
pizzeria only delivers between 11am and 9pm, and doesn’t promise anything better than 15 minute
increments, which we can mark up as follows:
<form> <div><label>Customer name: <input></label></div> <div><label>Telephone: <input type=tel></label></div> <div><label>E-mail address: <input type=email></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size> Small </label></div> <div><label> <input type=radio name=size> Medium </label></div> <div><label> <input type=radio name=size> Large </label></div> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <div><label> <input type=checkbox> Bacon </label></div> <div><label> <input type=checkbox> Extra Cheese </label></div> <div><label> <input type=checkbox> Onion </label></div> <div><label> <input type=checkbox> Mushroom </label></div> </fieldset> <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></div> </form>
The textarea
element can be used to provide a free-form text field. In this
instance, we are going to use it to provide a space for the customer to give delivery
instructions:
<form> <div><label>Customer name: <input></label></div> <div><label>Telephone: <input type=tel></label></div> <div><label>E-mail address: <input type=email></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size> Small </label></div> <div><label> <input type=radio name=size> Medium </label></div> <div><label> <input type=radio name=size> Large </label></div> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <div><label> <input type=checkbox> Bacon </label></div> <div><label> <input type=checkbox> Extra Cheese </label></div> <div><label> <input type=checkbox> Onion </label></div> <div><label> <input type=checkbox> Mushroom </label></div> </fieldset> <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></div> <div><label>Delivery instructions: <textarea></textarea></label></div> </form>
Finally, to make the form submittable we use the button
element:
<form> <div><label>Customer name: <input></label></div> <div><label>Telephone: <input type=tel></label></div> <div><label>E-mail address: <input type=email></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size> Small </label></div> <div><label> <input type=radio name=size> Medium </label></div> <div><label> <input type=radio name=size> Large </label></div> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <div><label> <input type=checkbox> Bacon </label></div> <div><label> <input type=checkbox> Extra Cheese </label></div> <div><label> <input type=checkbox> Onion </label></div> <div><label> <input type=checkbox> Mushroom </label></div> </fieldset> <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></div> <div><label>Delivery instructions: <textarea></textarea></label></div> <div><button>Submit order</button></div> </form>
4.10.1.2. Implementing the server-side processing for a form
This section is non-normative.
The exact details for writing a server-side processor are out of scope for this specification.
For the purposes of this introduction, we will assume that the script at https://pizza.example.com/order.cgi
is configured to accept submissions using the application/x-www-form-urlencoded
format,
expecting the following parameters sent in an HTTP POST body:
custname
-
Customer’s name
custtel
-
Customer’s telephone number
custemail
-
Customer’s e-mail address
size
-
The pizza size, either
small
,medium
, orlarge
topping
-
A topping, specified once for each selected topping, with the allowed values being
bacon
,cheese
,onion
, andmushroom
delivery
-
The requested delivery time
comments
-
The delivery instructions
4.10.1.3. Configuring a form to communicate with a server
This section is non-normative.
Form submissions are exposed to servers in a variety of ways, most commonly as HTTP GET or
POST requests. To specify the exact method used, the method
attribute is specified on the form
element. This doesn’t specify how the form data is
encoded, though; to specify that, you use the enctype
attribute. You also have to specify the URL of the service that will handle the
submitted data, using the action
attribute.
For each form control you want submitted, you then have to give a name that will be used to
refer to the data in the submission. We already specified the name for the group of radio buttons;
the same attribute (name
) also specifies the submission name.
Radio buttons can be distinguished from each other in the submission by giving them different
values, using the value
attribute.
Multiple controls can have the same name; for example, here we give all the checkboxes the same
name, and the server distinguishes which checkbox was checked by seeing which values are submitted
with that name — like the radio buttons, they are also given unique values with the value
attribute.
Given the settings in the previous section, this all becomes:
<form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname"></label></p> <p><label>Telephone: <input type=tel name="custtel"></label></p> <p><label>E-mail address: <input type=email name="custemail"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size value="small"> Small </label></p> <p><label> <input type=radio name=size value="medium"> Medium </label></p> <p><label> <input type=radio name=size value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery"></label></p> <p><label>Delivery instructions: <textarea name="comments"></textarea></label></p> <p><button>Submit order</button></p> </form>
There is no particular significance to the way some of the attributes have their values quoted and others don’t. The HTML syntax allows a variety of equally valid ways to specify attributes, as discussed in §8 The HTML syntax.
For example, if the customer entered "Denise Lawrence" as their name, "555-321-8642" as their telephone number, did not specify an e-mail address, asked for a medium-sized pizza, selected the Extra Cheese and Mushroom toppings, entered a delivery time of 7pm, and left the delivery instructions text field blank, the user agent would submit the following to the online Web service:
custname=Denise+Lawrence&custtel=555-321-8642&custemail=&size=medium&topping=cheese&topping=mushroom&delivery=19%3A00&comments=
4.10.1.4. Client-side form validation
This section is non-normative.
Forms can be annotated in such a way that the user agent will check the user’s input before the form is submitted. The server still has to verify the input is valid (since hostile users can easily bypass the form validation), but it allows the user to avoid the wait incurred by having the server be the sole checker of the user’s input.
The simplest annotation is the required
attribute,
which can be specified on input
elements to indicate that the form is not to be
submitted until a value is given. By adding this attribute to the customer name, pizza size, and
delivery time fields, we allow the user agent to notify the user when the user submits the form
without filling in those fields:
<form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname" required></label></p> <p><label>Telephone: <input type=tel name="custtel"></label></p> <p><label>E-mail address: <input type=email name="custemail"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p> <p><label>Delivery instructions: <textarea name="comments"></textarea></label></p> <p><button>Submit order</button></p> </form>
It is also possible to limit the length of the input, using the maxlength
attribute. By adding this to the textarea
element, we can limit users to 1000 characters, preventing them from writing huge essays to the
busy delivery drivers instead of staying focused and to the point:
<form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname" required></label></p> <p><label>Telephone: <input type=tel name="custtel"></label></p> <p><label>E-mail address: <input type=email name="custemail"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p> <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p> <p><button>Submit order</button></p> </form>
When a form is submitted, invalid
events are
fired at each form control that is invalid, and then at the form
element itself. This
can be useful for displaying a summary of the problems with the form, since typically the browser
itself will only report one problem at a time.
4.10.1.5. Enabling client-side automatic filling of form controls
This section is non-normative.
Some browsers attempt to aid the user by automatically filling form controls rather than having the user reenter their information each time. For example, a field asking for the user’s telephone number can be automatically filled with the user’s phone number.
To help the user agent with this, the autocomplete
attribute can be used to describe the field’s purpose. In the case of this form, we have three
fields that can be usefully annotated in this way: the information about who the pizza is to be
delivered to. Adding this information looks like this:
<form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <p><label>Customer name: <input name="custname" required autocomplete="shipping name"></label></p> <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p> <p><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size required value="small"> Small </label></p> <p><label> <input type=radio name=size required value="medium"> Medium </label></p> <p><label> <input type=radio name=size required value="large"> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p> <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p> <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p> <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p> <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p> <p><button>Submit order</button></p> </form>
4.10.1.6. Improving the user experience on mobile devices
This section is non-normative.
Some devices, in particular those with on-screen keyboards and those in locales with languages with many characters (e.g., Japanese), can provide the user with multiple input modalities. For example, when typing in a credit card number the user may wish to only see keys for digits 0-9, while when typing in their name they may wish to see a form field that by default capitalizes each word.
Using the inputmode
attribute we can select appropriate
input modalities:
<form method="post" enctype="application/x-www-form-urlencoded" action="https://pizza.example.com/order.cgi"> <div><label>Customer name: <input name="custname" required autocomplete="shipping name" inputmode="latin-name"></label></div> <div><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></div> <div><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></div> <fieldset> <legend> Pizza Size </legend> <div><label> <input type=radio name=size required value="small"> Small </label></div> <div><label> <input type=radio name=size required value="medium"> Medium </label></div> <div><label> <input type=radio name=size required value="large"> Large </label></div> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <div><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></div> <div><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></div> <div><label> <input type=checkbox name="topping" value="onion"> Onion </label></div> <div><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></divp> </fieldset> <div><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></divp> <div><label>Delivery instructions: <textarea name="comments" maxlength=1000 inputmode="latin-prose"></textarea></label></div> <div><button>Submit order</button></div> </form>
4.10.1.7. The difference between the field type, the autofill field name, and the input modality
This section is non-normative.
The type
, autocomplete
, and inputmode
attributes can seem confusingly similar. For instance,
in all three cases, the string "email
" is a valid value. This section
attempts to illustrate the difference between the three attributes and provides advice suggesting
how to use them.
The type
attribute on input
elements decides
what kind of control the user agent will use to expose the field. Choosing between different
values of this attribute is the same choice as choosing whether to use an input
element, a textarea
element, a select
element, etc.
The autocomplete
attribute, in contrast, describes
what the value that the user will enter actually represents. Choosing between different values of
this attribute is the same choice as choosing what the label for the element will be.
First, consider telephone numbers. If a page is asking for a telephone number from the user,
the right form control to use is <input type=tel>
.
However, which autocomplete
value to use depends on
which phone number the page is asking for, whether they expect a telephone number in the
international format or just the local format, and so forth.
For example, a page that forms part of a checkout process on an e-commerce site for a customer buying a gift to be shipped to a friend might need both the buyer’s telephone number (in case of payment issues) and the friend’s telephone number (in case of delivery issues). If the site expects international phone numbers (with the country code prefix), this could thus look like this:
<div><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel"></label> <div><label>Recipient’s phone number: <input type=tel name=shiptel autocomplete="shipping tel"></label> <p>Please enter complete phone numbers including the country code prefix, as in "+1 555 123 4567".
But if the site only supports British customers and recipients, it might instead look like this
(notice the use of tel-national
rather than tel
):
<div><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel-national"></label> <div><label>Recipient’s phone number: <input type=tel name=shiptel autocomplete="shipping tel-national"></label> <p>Please enter complete UK phone numbers, as in "(01632) 960 123".
Now, consider a person’s preferred languages. The right autocomplete
value is language
. However, there could be a number of
different form controls used for the purpose: a free text field (<input type=text>
), a drop-down list (<select>
), radio buttons (<input
type=radio>
), etc. It only depends on what kind of interface is desired.
The inputmode
decides what kind of input modality (e.g.,
keyboard) to use, when the control is a free-form text field.
Consider names. If a page just wants one name from the user, then the relevant control is <input type=text>
. If the page is asking for the user’s
full name, then the relevant autocomplete
value is name
. But if the user is Japanese, and the page is asking
for the user’s Japanese name and the user’s romanized name, then it would be helpful to the user
if the first field defaulted to a Japanese input modality, while the second defaulted to a Latin
input modality (ideally with automatic capitalization of each word). This is where the inputmode
attribute can help:
<p><label>Japanese name: <input name="j" type="text" autocomplete="section-jp name" inputmode="kana"></label> <label>Romanized name: <input name="e" type="text" autocomplete="section-en name" inputmode="latin-name"></label>
In this example, the "section-*
" keywords in
the autocomplete
attributes' values tell the user agent
that the two fields expect different names. Without them, the user agent could
automatically fill the second field with the value given in the first field when the user gave a
value to the first field.
The "-jp
" and "-en
" parts of the
keywords are opaque to the user agent; the user agent cannot guess, from those, that the two names
are expected to be in Japanese and English respectively.
4.10.1.8. Date, time, and number formats
This section is non-normative.
In this pizza delivery example, the times are specified in the format "HH:MM": two digits for the hour, in 24-hour format, and two digits for the time. (Seconds could also be specified, though they are not necessary in this example.)
In some locales, however, times are often expressed differently when presented to users. For example, in the United States, it is still common to use the 12-hour clock with an am/pm indicator, as in "2pm". In France, it is common to use the 24-hour clock, and separate the hours from the minutes using an "h" character, as in "14h00".
Similar issues exist with dates, with the added complication that even the order of the components is not always consistent — for example, in Cyprus the first of February 2003 would typically be written "1/2/03", while that same date in Japan would typically be written as "2003年02月01日" — and even with numbers, where locales differ, for example, in what punctuation is used as the decimal separator and the thousands separator.
It is therefore important to distinguish the time, date, and number formats used in HTML and in form submissions, which are always the formats defined in this specification (and based on the well-established ISO 8601 standard for computer-readable date and time formats), from the time, date, and number formats presented to the user by the browser and accepted as input from the user by the browser.
The format used "on the wire", i.e. in HTML markup and in form submissions, is intended to be computer-readable and consistent irrespective of the user’s locale. Dates, for instance, are always written in the format "YYYY-MM-DD", as in "2003-02-01". Users are not expected to ever see this format.
The time, date, or number given by the page in the wire format is then translated to the user’s preferred presentation (based on user preferences or on the locale of the page itself), before being displayed to the user. Similarly, after the user inputs a time, date, or number using their preferred format, the user agent converts it back to the wire format before putting it in the DOM or submitting it.
This allows scripts in pages and on servers to process times, dates, and numbers in a consistent manner without needing to support dozens of different formats, while still supporting the users' needs.
See also the implementation notes regarding localization of form controls.
In locales where the clocks change from Standard Time to Daylight Saving Time, the same time can occur twice in the same day when the clocks are moved backwards. An input
element with a the type
of datetime
or time
cannot differentiate between two identical instances of time. If the accuracy of entered time is important, users should therefore be given the option to specify which occurance of the duplicated time they want to enter.
4.10.2. Categories
Mostly for historical reasons, elements in this section fall into several overlapping (but subtly different) categories in addition to the usual ones like flow content, phrasing content, and interactive content.
A number of the elements are form-associated elements, which means they can have a form owner.
The form-associated elements fall into several subcategories:
- Listed elements
-
Denotes elements that are listed in the
form.elements
andfieldset.elements
APIs. - Submittable elements
-
Denotes elements that can be used for constructing the form data set when a
form
element is submitted.Some submittable elements can be, depending on their attributes, buttons. The prose below defines when an element is a button. Some buttons are specifically submit buttons.
- Resettable elements
-
Denotes elements that can be affected when a
form
element is reset. - Reassociateable elements
-
Denotes elements that have a
form
content attribute, and a matchingform
IDL attribute, that allow authors to specify an explicit form owner.
Some elements, not all of them form-associated,
are categorized as labelable elements. These are elements that
can be associated with a label
element.
The following table is non-normative and summarizes the above categories of form elements:
form-associated | listed | submittable | resettable | reassociateable | labelable | |
---|---|---|---|---|---|---|
can have a form owner | listed in the form.elements and fieldset.elements APIs
| can be used for constructing the form data set when a form element is submitted | can be affected when a form element is reset | have a form attribute (allows authors to specify an explicit form owner)
| can be associated with a label element
| |
input
| yes | yes | yes | yes | yes | yes (except "hidden") |
button
| yes | yes | yes | no | yes | yes |
select
| yes | yes | yes | yes | yes | yes |
textarea
| yes | yes | yes | yes | yes | yes |
fieldset
| yes | yes | no | no | yes | no |
output
| yes | yes | no | yes | yes | yes |
object
| yes | yes | yes | no | yes | no |
meter
| no | no | no | no | no | yes |
progress
| no | no | no | no | no | yes |
label
| yes | no | no | no | no | no |
img
| yes | no | no | no | no | no |
4.10.3. The form
element
- Categories:
- Flow content.
- Palpable content.
- Contexts in which this element can be used:
- Where flow content is expected.
- Content model:
- Flow content, but with no
form
element descendants. - Tag omission in text/html:
- Neither tag is omissible.
- Content attributes:
- Global attributes
accept-charset
- Character encodings to use for §4.10.21 Form submissionaction
- URL to use for §4.10.21 Form submissionautocomplete
- Default setting for autofill feature for controls in the formenctype
- Form data set encoding type to use for §4.10.21 Form submissionmethod
- HTTP method to use for §4.10.21 Form submissionname
- Name of form to use in thedocument.forms
APInovalidate
- Bypass form control validation for §4.10.21 Form submissiontarget
- browsing context for §4.10.21 Form submission- Allowed ARIA role attribute values:
dd>
form
(default - do not set),search
orpresentation
. - Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles. - DOM interface:
-
[OverrideBuiltins] interface HTMLFormElement : HTMLElement { attribute DOMString acceptCharset; attribute DOMString action; attribute DOMString autocomplete; attribute DOMString enctype; attribute DOMString encoding; attribute DOMString method; attribute DOMString name; attribute boolean noValidate; attribute DOMString target; [SameObject] readonly attribute HTMLFormControlsCollection elements; readonly attribute unsigned long length; getter Element (unsigned long index); getter (RadioNodeList or Element) (DOMString name); void submit(); void reset(); boolean checkValidity(); boolean reportValidity(); };
The form
element represents a collection of form-associated elements, some of which can represent
editable values that can be submitted to a server for processing.
The accept-charset
content attribute gives the
character encodings that are to be used for the submission. If specified, the value must be an ordered set of unique space-separated tokens that are ASCII
case-insensitive, and each token must be an ASCII case-insensitive match for
one of the labels of an ASCII-compatible encoding. [ENCODING]
The name
content attribute represents the form
's name within the forms
collection. The
value must not be the empty string, and the value must be unique amongst the form
elements in the forms
collection that it is in, if any.
The autocomplete
content attribute is an enumerated attribute. The attribute has two states. The on
keyword maps to the on state, and the off
keyword maps to the off state. The attribute may also be omitted. The missing value default is the on state. The off state indicates that by default, form
controls in the form will have their autofill field name set to "off
"; the on state indicates that by default, form controls
in the form will have their autofill field name set to "on
".
The action
, enctype
, method
, enctype
, novalidate
, and target
attributes are attributes for form submission.
- form .
elements
-
Returns an
HTMLFormControlsCollection
of the form controls in the form (excluding image buttons for historical reasons). - form .
length
-
Returns the number of form controls in the form (excluding image buttons for historical reasons).
- form[index]
-
Returns the indexth element in the form (excluding image buttons for historical reasons).
- form[name]
-
Returns the form control (or, if there are several, a
RadioNodeList
of the form controls) in the form with the given ID orname
(excluding image buttons for historical reasons); or, if there are none, returns theimg
element with the given ID.Once an element has been referenced using a particular name, that name will continue being available as a way to reference that element in this method, even if the element’s actual ID or
name
changes, for as long as the element remains in theDocument
.If there are multiple matching items, then a
RadioNodeList
object containing all those elements is returned. - form .
submit()
-
Submits the form.
- form .
reset()
-
Resets the form.
- form .
checkValidity()
-
Returns true if the form’s controls are all valid; otherwise, returns false.
- form .
reportValidity()
-
Returns true if the form’s controls are all valid; otherwise, returns false and informs the user.
The autocomplete
IDL attribute must reflect the content attribute of the same name, limited to only known
values.
The name
IDL attribute must reflect the content attribute of the same name.
The acceptCharset
IDL attribute must reflect the accept-charset
content attribute.
The elements
IDL attribute must return an HTMLFormControlsCollection
rooted at the form
element, whose filter matches listed elements whose form owner is the form
element, with the exception of input
elements whose type
attribute is in the Image Button
state, which must, for historical reasons, be
excluded from this particular collection.
The length
IDL attribute must return the
number of nodes represented by the elements
collection.
The supported property indices at any instant are the indices supported by the
object returned by the elements
attribute at that
instant.
When a form
element is indexed for indexed property
retrieval, the user agent must return the value returned by the item
method on the elements
collection, when invoked with the given index as its
argument.
Each form
element has a mapping of names to elements called the past names
map. It is used to persist names of controls even when they change names.
The supported property names consist of the names obtained from the following algorithm, in the order obtained from this algorithm:
- Let sourced names be an initially empty ordered list of tuples consisting of a string, an element, a source, where the source is either id, name, or past, and, if the source is past, an age.
-
For each listed element candidate whose form owner is the
form
element, with the exception of anyinput
elements whosetype
attribute is in theImage Button
state, run these substeps:- If candidate has an
id
attribute, add an entry to sourced names with thatid
attribute’s value as the string, candidate as the element, and id as the source. - If candidate has a
name
attribute, add an entry to sourced names with thatname
attribute’s value as the string, candidate as the element, and name as the source.
- If candidate has an
-
For each
img
element candidate whose form owner is theform
element, run these substeps:- If candidate has an
id
attribute, add an entry to sourced names with thatid
attribute’s value as the string, candidate as the element, and id as the source. - If candidate has a
name
attribute, add an entry to sourced names with thatname
attribute’s value as the string, candidate as the element, and name as the source.
- If candidate has an
-
For each entry past entry in the past names map add an entry to sourced names with the past entry’s name as the string, past entry’s element as the element, past as the source, and the length of time past entry has been in the past names map as the age.
- Sort sourced names by tree order of the element entry of each tuple, sorting entries with the same element by putting entries whose source is id first, then entries whose source is name, and finally entries whose source is past, and sorting entries with the same element and source by their age, oldest first.
- Remove any entries in sourced names that have the empty string as their name.
- Remove any entries in sourced names that have the same name as an earlier entry in the map.
- Return the list of names from sourced names, maintaining their relative order.
The properties exposed in this way must be unenumerable.
When a form
element is indexed for named property retrieval, the user agent must
run the following steps:
-
Let candidates be a live
RadioNodeList
object containing all the listed elements whose form owner is theform
element that have either anid
attribute or aname
attribute equal to name, with the exception ofinput
elements whosetype
attribute is in theImage Button
state, in tree order. -
If candidates is empty, let candidates be a live
RadioNodeList
object containing all theimg
elements that are descendants of theform
element and that have either anid
attribute or aname
attribute equal to name, in tree order. -
If candidates is empty, name is the name of one of the entries in the
form
element’s past names map: return the object associated with name in that map. -
If candidates contains more than one node, return candidates and abort these steps.
-
Otherwise, candidates contains exactly one node. Add a mapping from name to the node in candidates in the
form
element’s past names map, replacing the previous entry with the same name, if any. -
Return the node in candidates.
If an element listed in a form
element’s past names map changes form owner, then
its entries must be removed from that map.
The submit()
method, when invoked, must submit the form
element from the form
element itself, with the submitted from submit()
method flag set.
The reset()
method, when invoked, must run
the following steps:
- If the
form
element is marked as locked for reset, then abort these steps. - Mark the
form
element as locked for reset. - Reset the
form
element. - Unmark the
form
element as locked for reset.
If the checkValidity()
method is
invoked, the user agent must statically validate the constraints of the form
element, and return true if the constraint validation return a positive result, and false if it returned a negative result.
If the reportValidity()
method is
invoked, the user agent must interactively validate the constraints of the form
element, and return true if the constraint validation return a positive result, and false if it returned a negative result.
<form action="https://www.google.com/search" method="get"> <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search..."> </form> <form action="https://www.bing.com/search" method="get"> <label>Bing: <input type="search" name="q"></label> <input type="submit" value="Search..."> </form>
4.10.4. The label
element
- Categories:
- Flow content.
- Phrasing content.
- Interactive content.
- form-associated element.
- Palpable content.
- Contexts in which this element can be used:
- Where phrasing content is expected.
- Content model:
- Phrasing content, but with no descendant labelable elements unless it is the element’s labeled control, and no descendant
label
elements. - Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
for
- Associate the label with form control- Allowed ARIA role attribute values:
- None
- Allowed ARIA state and property attributes:
- Global aria-* attributes
- DOM interface:
-
interface HTMLLabelElement : HTMLElement { readonly attribute HTMLFormElement? form; attribute DOMString htmlFor; readonly attribute HTMLElement? control; };
The label
element represents a caption in a user interface. The
caption can be associated with a specific form control, known as the label
element’s labeled control, either using the for
attribute,
or by putting the form control inside the label
element itself.
Except where otherwise specified by the following rules, a label
element has no labeled control.
The for
attribute may be specified to indicate a
form control with which the caption is to be associated. If the attribute is specified, the
attribute’s value must be the ID of a labelable element in the same Document
as the label
element. If the attribute is specified and there is an
element in the Document
whose ID is equal to the
value of the for
attribute, and the first such element is a labelable element, then that element is the label
element’s labeled control.
The following example shows the use of a for
attribute, to associate label
s
which do not contain the element they label.
<form> <table> <caption>Example, <label>'s for attribute</caption> <tr> <th><label for="name">Customer name: </label></th> <td><input name="name" id="name"></td> </tr> </table> </form>
Note that the id
attribute is required to associate the for
attribute,
while the name
attribute is required so the value of the input will be submitted as
part of the form.
If the for
attribute is not specified, but the label
element has a labelable element descendant,
then the first such descendant in tree order is the label
element’s labeled control.
The label
element’s activation behavior should match the platform’s label
behavior. Similarly, any additional presentation hints should match the platform’s
label presentation.
label
"Lost" in the following
snippet could trigger the user agent to run synthetic click activation steps on the checkbox, as if the element itself had been triggered by the user, while clicking
the label
"Where?" would queue a task that runs the focusing steps for the element to the text input:
<label><input type="checkbox" name="lost"> Lost</label><br> <label>Where? <input type="text" name="where"></label>
If a label
element has interactive content other than its labeled control, the activation behavior of the label
element for events targeted
at those interactive content descendants and any
descendants of those must be to do nothing.
In the following example, clicking on the link does not toggle the checkbox, even if the platform normally toggles a checkbox when clicking on a label. Instead, clicking the link triggers the normal activation behavior of following the link.
<!-- bad example - link inside label reduces checkbox activation area --> <label><input type=checkbox name=tac>I agree to <a href="tandc.html">the terms and conditions</a></label>
The ability to click or press a label
to trigger an event on a control provides
usability and accessibility benefits by increasing the hit area of a control, making it easier for a user to operate.
These benefits may be lost or reduced, if the label
element contains an element with its own activation
behavior, such as a link:
<!-- bad example - all label text inside the link reduces activation area to checkbox only --> <label><input type=checkbox name=tac><a href="tandc.html">I agree to the terms and conditions</a></label>
The usability and accessibility benefits can be maintained by placing such elements outside the label
element:
<!-- good example - link outside label means checkbox activation area includes the checkbox and all the label text --> <label><input type=checkbox name=tac>I agree to the terms and conditions</label> (read <a href="tandc.html">Terms and Conditions</a>)
<p><label>Full name: <input name=fn> <small>Format: First Last</small></label></p> <p><label>Age: <input name=age type=number min=0></label></p> <p><label>Post code: <input name=pc> <small>Format: AB12 3CD</small></label></p>
- label .
control
-
Returns the form control that is associated with this element.
The htmlFor
IDL attribute must reflect the for
content attribute.
The control
IDL attribute must return the label
element’s labeled control, if any, or null if there isn’t one.
- control .
labels
-
Returns a
NodeList
of all thelabel
elements that the form control is associated with.
Labelable elements have a NodeList
object
associated with them that represents the list of label
elements, in tree
order, whose labeled control is the element in question. The labels
IDL attribute of labelable elements, on getting, must return that NodeList
object.
4.10.5. The input
element
- Categories:
- Flow content.
- Phrasing content.
- If the
type
attribute is not in theHidden
state: interactive content. - If the
type
attribute is not in theHidden
state: listed, labelable, submittable, resettable, and reassociateable form-associated element. - If the
type
attribute is in theHidden
state: listed, submittable, resettable, and reassociateable form-associated element. - If the
type
attribute is not in theHidden
state: Palpable content. - Contexts in which this element can be used:
- Where phrasing content is expected.
- Content model:
- Nothing.
- Tag omission in text/html:
- No end tag
- Content attributes:
- Global attributes
accept
- Hint for expected file type inFile Upload
controlsalt
- Replacement text for use when images are not availableautocomplete
- Hint for form autofill featureautofocus
- Automatically focus the form control when the page is loadedchecked
- Whether the command or control is checkeddirname
- Name of form field to use for sending the element’s directionality in §4.10.21 Form submissiondisabled
- Whether the form control is disabledform
- Associates the control with aform
elementformaction
- URL to use for §4.10.21 Form submissionformenctype
- Form data set encoding type to use for §4.10.21 Form submissionformmethod
- HTTP method to use for §4.10.21 Form submissionformnovalidate
- Bypass form control validation for §4.10.21 Form submissionformtarget
- browsing context for §4.10.21 Form submissionheight
- Vertical dimensioninputmode
- Hint for selecting an input modalitylist
- List of autocomplete optionsmax
- Maximum valuemaxlength
- Maximum length of valuemin
- Minimum valueminlength
- Minimum length of valuemultiple
- Whether to allow multiple valuesname
- Name of form control to use for §4.10.21 Form submission and in theform.elements
APIpattern
- Pattern to be matched by the form control’s valueplaceholder
- User-visible label to be placed within the form controlreadonly
- Whether to allow the value to be edited by the userrequired
- Whether the control is required for §4.10.21 Form submissionsize
- Size of the controlsrc
- Address of the resourcestep
- Granularity to be matched by the form control’s valuetype
- Type of form controlvalue
- Value of the form controlwidth
- Horizontal dimension- Also, the
title
attribute has special semantics on this element when used in conjunction with thepattern
attribute. - Allowed ARIA role attribute values:
- Depends upon state of the
type
attribute. - Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles. - DOM interface:
-
interface HTMLInputElement : HTMLElement { attribute DOMString accept; attribute DOMString alt; attribute DOMString autocomplete; attribute boolean autofocus; attribute boolean defaultChecked; attribute boolean checked; attribute DOMString dirName; attribute boolean disabled; readonly attribute HTMLFormElement? form; readonly attribute FileList? files; attribute DOMString formAction; attribute DOMString formEnctype; attribute DOMString formMethod; attribute boolean formNoValidate; attribute DOMString formTarget; attribute unsigned long height; attribute boolean indeterminate; attribute DOMString inputMode; readonly attribute HTMLElement? list; attribute DOMString max; attribute long maxLength; attribute DOMString min; attribute long minLength; attribute boolean multiple; attribute DOMString name; attribute DOMString pattern; attribute DOMString placeholder; attribute boolean readOnly; attribute boolean _required; attribute unsigned long size; attribute DOMString src; attribute DOMString step; attribute DOMString type; attribute DOMString defaultValue; [TreatNullAs=EmptyString] attribute DOMString value; attribute object? valueAsDate; attribute unrestricted double valueAsNumber; attribute unsigned long width; void stepUp(optional long n = 1); void stepDown(optional long n = 1); readonly attribute boolean willValidate; readonly attribute ValidityState validity; readonly attribute DOMString validationMessage; boolean checkValidity(); boolean reportValidity(); void setCustomValidity(DOMString error); [SameObject] readonly attribute NodeList labels; void select(); attribute unsigned long? selectionStart; attribute unsigned long? selectionEnd; attribute DOMString? selectionDirection; void setRangeText(DOMString replacement); void setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve"); void setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction); };
The input
element represents a typed data field, usually with a form
control to allow the user to edit the data.
The type
attribute controls the data type of the
element. It is an enumerated attribute. The data type is used to select the control to
use for the input
. Some data types allow either a text field or combo box control to be used,
based on the absence or presence of a list
attribute on the element.
The following table lists the keywords and states for the attribute — the keywords in the
left column map to the state, data type and control(s) in the cells on the same row.
Keyword | State | Data type | Control type |
---|---|---|---|
hidden
|
| An arbitrary string | n/a |
text
| Text
| Text with no line breaks | A text field or combo box |
search
| Search
| Text with no line breaks | Search field or combo box |
tel
| Telephone
| Text with no line breaks | A text field or combo box |
url
| URL
| An absolute URL | A text field or combo box |
email
| E-mail
| An e-mail address or list of e-mail addresses | A text field or combo box |
password
| Password
| Text with no line breaks (sensitive information) | A text field that obscures data entry |
datetime
| Date and Time
| A date and time (year, month, day, hour, minute, second, fraction of a second) with the time zone set to UTC | A date and time control |
date
| Date
| A date (year, month, day) with no time zone | A date control |
month
| Month
| A date consisting of a year and a month with no time zone | A month control |
week
| Week
| A date consisting of a week-year number and a week number with no time zone | A week control |
time
| Time
| A time (hour, minute, seconds, fractional seconds) with no time zone | A time control |
datetime-local
| Local Date and Time
| A date and time (year, month, day, hour, minute, second, fraction of a second) with no timezone offset | A date and time control |
number
| Number
| A numerical value | A text field or combo box or spinner control |
range
| Range
| A numerical value, with the extra semantic that the exact value is not important | A slider control or similar |
color
| Color
| An sRGB color with 8-bit red, green, and blue components | A color well |
checkbox
| Checkbox
| A set of zero or more values from a predefined list | A checkbox |
radio
| Radio Button
| An enumerated value | A radio button |
file
| File Upload
| Zero or more files each with a MIME type and optionally a file name | A label and a button |
submit
| Submit Button
| An enumerated value, with the extra semantic that it must be the last value selected and initiates form submission | A button |
image
| Image Button
| A coordinate, relative to a particular image’s size, with the extra semantic that it must be the last value selected and initiates form submission | Either a clickable image, or a button |
reset
| Reset Button
| n/a | A button |
button
| Button
| n/a | A button |
The missing value default is the Text state.
Which of the accept
, alt
, autocomplete
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, src
, step
, and width
content attributes, the checked
, files
, valueAsDate
, valueAsNumber
, and list
IDL attributes, the select()
method, the selectionStart
, selectionEnd
, and selectionDirection
, IDL attributes, the setRangeText()
and setSelectionRange()
methods, the stepUp()
and stepDown()
methods, and the input
and change
events apply to an input
element depends on the state of its type
attribute.
The subsections that define each type also clearly define in normative "bookkeeping" sections
which of these feature apply, and which do not apply, to each type. The behavior of
these features depends on whether they apply or not, as defined in their various sections (q.v.
for Content attributes, for APIs, for events).
The following table is non-normative and summarizes which of those content attributes, IDL attributes, methods, and events apply to each state:
| Text , Search
| URL , Telephone
| E-mail
| Password
| Date and Time , Date , Month , Week , Time
| Number
| Range
| Color
| Checkbox , Radio Button
| File Upload
| Submit Button
| Image Button
| Reset Button , Button
| |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Content attributes | ||||||||||||||
accept
| · | · | · | · | · | · | · | · | · | · | Yes | · | · | · |
alt
| · | · | · | · | · | · | · | · | · | · | · | · | Yes | · |
autocomplete
| · | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | · | · | · | · | · |
checked
| · | · | · | · | · | · | · | · | · | Yes | · | · | · | · |
dirname
| · | Yes | · | · | · | · | · | · | · | · | · | · | · | · |
formaction
| · | · | · | · | · | · | · | · | · | · | · | Yes | Yes | · |
formenctype
| · | · | · | · | · | · | · | · | · | · | · | Yes | Yes | · |
formmethod
| · | · | · | · | · | · | · | · | · | · | · | Yes | Yes | · |
formnovalidate
| · | · | · | · | · | · | · | · | · | · | · | Yes | Yes | · |
formtarget
| · | · | · | · | · | · | · | · | · | · | · | Yes | Yes | · |
height
| · | · | · | · | · | · | · | · | · | · | · | · | Yes | · |
inputmode
| · | Yes | · | · | Yes | · | · | · | · | · | · | · | · | · |
list
| · | Yes | Yes | Yes | · | Yes | Yes | Yes | Yes | · | · | · | · | · |
max
| · | · | · | · | · | Yes | Yes | Yes | · | · | · | · | · | · |
maxlength
| · | Yes | Yes | Yes | Yes | · | · | · | · | · | · | · | · | · |
min
| · | · | · | · | · | Yes | Yes | Yes | · | · | · | · | · | · |
minlength
| · | Yes | Yes | Yes | Yes | · | · | · | · | · | · | · | · | · |
multiple
| · | · | · | Yes | · | · | · | · | · | · | Yes | · | · | · |
pattern
| · | Yes | Yes | Yes | Yes | · | · | · | · | · | · | · | · | · |
placeholder
| · | Yes | Yes | Yes | Yes | · | Yes | · | · | · | · | · | · | · |
readonly
| · | Yes | Yes | Yes | Yes | Yes | Yes | · | · | · | · | · | · | · |
required
| · | Yes | Yes | Yes | Yes | Yes | Yes | · | · | Yes | Yes | · | · | · |
size
| · | Yes | Yes | Yes | Yes | · | · | · | · | · | · | · | · | · |
src
| · | · | · | · | · | · | · | · | · | · | · | · | Yes | · |
step
| · | · | · | · | · | Yes | Yes | Yes | · | · | · | · | · | · |
width
| · | · | · | · | · | · | · | · | · | · | · | · | Yes | · |
IDL attributes and methods | ||||||||||||||
checked
| · | · | · | · | · | · | · | · | · | Yes | · | · | · | · |
files
| · | · | · | · | · | · | · | · | · | · | Yes | · | · | · |
value
| default | value | value | value | value | value | value | value | value | default/on | filename | default | default | default |
valueAsDate
| · | · | · | · | · | Yes | · | · | · | · | · | · | · | · |
valueAsNumber
| · | · | · | · | · | Yes | Yes | Yes | · | · | · | · | · | · |
list
| · | Yes | Yes | Yes | · | Yes | Yes | Yes | Yes | · | · | · | · | · |
select()
| · | Yes | Yes† | Yes | Yes† | Yes† | Yes† | · | Yes† | · | Yes† | · | · | · |
selectionStart
| · | Yes | Yes | · | Yes | · | · | · | · | · | · | · | · | · |
selectionEnd
| · | Yes | Yes | · | Yes | · | · | · | · | · | · | · | · | · |
selectionDirection
| · | Yes | Yes | · | Yes | · | · | · | · | · | · | · | · | · |
setRangeText()
| · | Yes | Yes | · | Yes | · | · | · | · | · | · | · | · | · |
setSelectionRange()
| · | Yes | Yes | · | Yes | · | · | · | · | · | · | · | · | · |
stepDown()
| · | · | · | · | · | Yes | Yes | Yes | · | · | · | · | · | · |
stepUp()
| · | · | · | · | · | Yes | Yes | Yes | · | · | · | · | · | · |
Events | ||||||||||||||
input event
| · | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | · | · | · |
change event
| · | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | · | · | · |
† If the control has no text field, the select()
method
results in a no-op, with no "InvalidStateError
" DOMException
.
Some states of the type
attribute define a value sanitization algorithm.
Each input
element has a value, which is
exposed by the value
IDL attribute. Some states define an algorithm to convert a string to a number,
an algorithm to convert a number to a
string, an algorithm to convert a string to a Date
object, and an algorithm to
convert a Date
object to a string, which are used by max
, min
, step
, valueAsDate
, valueAsNumber
, stepDown()
, and stepUp()
.
Each input
element has a boolean dirty value flag. The dirty value flag must be
initially set to false when the element is created, and must be set to true whenever the user
interacts with the control in a way that changes the value.
(It is also set to true when the value is programmatically changed, as described in the definition
of the value
IDL attribute.)
The value
content attribute gives the default value of the input
element. When the value
content attribute is added,
set, or removed, if the control’s dirty value flag is false, the user agent must set the value of the element
to the value of the value
content attribute, if there is
one, or the empty string otherwise, and then run the current value sanitization
algorithm, if one is defined.
Each input
element has a checkedness,
which is exposed by the checked
IDL attribute.
Each input
element has a boolean dirty checkedness flag. When it is true, the
element is said to have a dirty checkedness.
The dirty checkedness flag must be initially
set to false when the element is created, and must be set to true whenever the user interacts with
the control in a way that changes the checkedness.
The checked
content attribute is a boolean attribute that gives the default checkedness of the input
element.
When the checked
content attribute is added,
if the control does not have dirty checkedness, the
user agent must set the checkedness of the element to
true; when the checked
content attribute is removed, if
the control does not have dirty checkedness, the user
agent must set the checkedness of the element to
false.
The reset algorithm for input
elements is to set the dirty value flag and dirty checkedness flag back to false, set
the value of the element to the value of the value
content attribute,
if there is one, or the empty string
otherwise, set the checkedness of the element to true if
the element has a checked
content attribute and false if
it does not, empty the list of selected
files, and then invoke the value sanitization algorithm,
if the type
attribute’s current state defines one.
Each input
element can be mutable. Except where
otherwise specified, an input
element is always mutable. Similarly,
except where otherwise specified, the user agent should not allow the user to
modify the element’s value or checkedness.
When an input
element is disabled, it is not mutable.
The readonly
attribute can also in some
cases (e.g., for the Date
state, but not the Checkbox
state) stop an input
element from being mutable.
The cloning steps for input
elements
must propagate the value, dirty value flag, checkedness, and dirty checkedness flag from the node being cloned
to the copy.
When an input
element is first created, the element’s rendering and behavior must
be set to the rendering and behavior defined for the type
attribute’s state, and the value sanitization algorithm, if one is defined for the type
attribute’s state, must be invoked.
When an input
element’s type
attribute
changes state, the user agent must run the following steps:
- If the previous state of the element’s
type
attribute put thevalue
IDL attribute in the value mode, and the element’s value is not the empty string, and the new state of the element’stype
attribute puts thevalue
IDL attribute in either the default mode or the default/on mode, then set the element’svalue
content attribute to the element’s value. - Otherwise, if the previous state of the element’s
type
attribute put thevalue
IDL attribute in any mode other than the value mode, and the new state of the element’stype
attribute puts thevalue
IDL attribute in the value mode, then set the value of the element to the value of thevalue
content attribute, if there is one, or the empty string otherwise, and then set the control’s dirty value flag to false. - Otherwise, if the previous state of the element’s
type
attribute put thevalue
IDL attribute in any mode other than the filename mode, and the new state of the element’stype
attribute puts thevalue
IDL attribute in the filename mode, then set the value of the element to the empty string. - Update the element’s rendering and behavior to the new state’s.
- Signal a type change for the element. (The
Radio Button
state uses this, in particular.) - Invoke the value sanitization algorithm, if one is defined for the
type
attribute’s new state.
The name
attribute represents the element’s name.
The dirname
attribute controls how the element’s directionality is submitted.
The disabled
attribute is used to make the control non-interactive and to prevent its value from being submitted.
The form
attribute is used to explicitly associate the input
element with its form owner.
The autofocus
attribute controls focus.
The inputmode
attribute controls the user interface’s input modality for the control.
The autocomplete
attribute controls how the user agent provides autofill behavior.
The indeterminate
IDL attribute must
initially be set to false. On getting, it must return the last value it was set to. On setting, it
must be set to the new value. It has no effect except for changing the appearance of checkbox
controls.
The accept
, alt
, max
, min
, multiple
, pattern
, placeholder
, required
, size
, src
, and step
IDL attributes must reflect the respective content attributes of the same name.
The dirName
IDL attribute must reflect the dirname
content attribute.
The readOnly
IDL attribute must reflect the readonly
content attribute.
The defaultChecked
IDL attribute must reflect the checked
content attribute.
The defaultValue
IDL attribute must reflect the value
content attribute.
The type
IDL attribute must reflect the respective content attribute of the same name, limited to only known values.
The inputMode
IDL attribute must reflect the inputmode
content attribute, limited to only known values.
The maxLength
IDL attribute must reflect the maxlength
content attribute, limited to only non-negative numbers.
The minLength
IDL attribute must reflect the minlength
content attribute, limited to only non-negative numbers.
The IDL attributes width
and height
must return the rendered
width and height of the image, in CSS pixels, if an image is being rendered, and is
being rendered to a visual medium; or else the intrinsic width and height of the image,
in CSS pixels, if an image is available but not being rendered to a visual medium;
or else 0, if no image is available. When the input
element’s type
attribute is not in the Image Button
state,
then no image is available. [CSS-2015]
On setting, they must act as if they reflected the respective content attributes of the same name.
The willValidate
, validity
, and validationMessage
IDL attributes, and
the checkValidity()
, reportValidity()
, and setCustomValidity()
methods, are part of
the constraint validation API.
The labels
IDL attribute provides a list of the element’s label
s.
The select()
, selectionStart
, selectionEnd
, selectionDirection
, setRangeText()
, and setSelectionRange()
methods and IDL
attributes expose the element’s text selection.
The autofocus
, disabled
, form
, and name
IDL attributes are part of the
element’s forms API.
4.10.5.1. States of the type
attribute
4.10.5.1.1. Hidden state (type=hidden
)
When an input
element’s type
attribute is in
the state, the rules in this section apply.
The input
element represents a value that is not intended to be
examined or manipulated by the user.
Constraint validation: If an input
element’s type
attribute is in the state, it is barred from constraint
validation.
If the name
attribute is present and has a value that is a case-sensitive match for the string "_charset_
", then the element’s value
attribute must be omitted.
The value
IDL attribute applies to this element and is
in mode default.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, autocomplete
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
The input
and change
events do not apply.
4.10.5.1.2. Text (type=text
) state and Search state (type=search
)
- Allowed ARIA role attribute values:
textbox
,searchbox
with nolist
attribute (default - do not set) or with alist
attribute:combobox
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Text
state or the Search
state, the rules in this section apply.
The input
element represents a one line plain text edit control for
the element’s value.
The difference between the Text
state
and the Search
state is primarily stylistic: on
platforms where search fields are distinguished from regular text fields, the Search
state might result in an appearance consistent with
the platform’s search fields rather than appearing like a regular text field.
If the element is mutable, its value should be editable by the user. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the element’s value.
If the element is mutable, the user agent should allow the user to change the writing direction of the element, setting it either to a left-to-right writing direction or a right-to-left writing direction. If the user does so, the user agent must then run the following steps:
- Set the element’s
dir
attribute to "ltr" if the user selected a left-to-right writing direction, and "rtl
" if the user selected a right-to-left writing direction. - Queue a task to fire a simple event that bubbles named
input
at theinput
element.
The value
attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
The value sanitization algorithm is as follows: Strip line breaks from the value.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, dirname
, inputmode
, list
, maxlength
, minlength
, pattern
, placeholder
, readonly
, required
, and size
content attributes; list
, selectionStart
, selectionEnd
, selectionDirection
, and value
IDL attributes; select()
, setRangeText()
, and setSelectionRange()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, max
, min
, multiple
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, valueAsDate
, and valueAsNumber
IDL attributes; stepDown()
and stepUp()
methods.
4.10.5.1.3. Telephone state (type=tel
)
- Allowed ARIA role attribute values:
textbox
with nolist
attribute (default - do not set) or with alist
attribute:combobox
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Telephone
state, the rules in this section apply.
The input
element represents a control for editing a telephone number
given in the element’s value.
If the element is mutable, its value should be editable by the user. User agents may change the spacing and, with care, the punctuation of values that the user enters. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the element’s value.
The value
attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
The value sanitization algorithm is as follows: Strip line breaks from the value.
Unlike the URL
and E-mail
types, the Telephone
type does not enforce a particular syntax. This is
intentional; in practice, telephone number fields tend to be free-form fields, because there are a
wide variety of valid phone numbers. Systems that need to enforce a particular format are
encouraged to use the pattern
attribute or the setCustomValidity()
method to hook into the client-side
validation mechanism.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, maxlength
, minlength
, pattern
, placeholder
, readonly
, required
, and size
content attributes; list
, selectionStart
, selectionEnd
, selectionDirection
, and value
IDL attributes; select()
, setRangeText()
, and setSelectionRange()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, max
, min
, multiple
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, valueAsDate
, and valueAsNumber
IDL attributes; stepDown()
and stepUp()
methods.
4.10.5.1.4. URL state (type=url
)
- Allowed ARIA role attribute values:
textbox
with nolist
attribute (default - do not set) or with alist
attribute:combobox
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the URL
state, the rules in this section apply.
The input
element represents a control for editing a single absolute URL given in the element’s value.
If the element is mutable, the user agent should allow the user to change the URL represented by its value. User agents may allow the user to set the value to a string that is not a valid absolute URL, but may also or instead automatically escape characters entered by the user so that the value is always a valid absolute URL (even if that isn’t the actual value seen and edited by the user in the interface). User agents should allow the user to set the value to the empty string. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the value.
The value
attribute, if specified and not empty, must
have a value that is a valid URL potentially surrounded by spaces that is also an absolute URL.
The value sanitization algorithm is as follows: Strip line breaks from the value, then strip leading and trailing white space from the value.
Constraint validation: While the value of the element is neither the empty string nor a valid absolute URL, the element is suffering from a type mismatch.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, maxlength
, minlength
, pattern
, placeholder
, readonly
, required
, and size
content attributes; list
, selectionStart
, selectionEnd
, selectionDirection
, and value
IDL attributes; select()
, setRangeText()
, and setSelectionRange()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, max
, min
, multiple
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, valueAsDate
, and valueAsNumber
IDL attributes; stepDown()
and stepUp()
methods.
<input type="url" name="location" list="urls"> <datalist id="urls"> <option label="MIME: Format of Internet Message Bodies" value="https://tools.ietf.org/html/rfc2045"> <option label="HTML 4.01 Specification" value="https://www.w3.org/TR/html4/"> <option label="Form Controls" value="https://www.w3.org/TR/xforms/slice8.html#ui-commonelems-hint"> <option label="Scalable Vector Graphics (SVG) 1.1 Specification" value="https://www.w3.org/TR/SVG/"> <option label="Feature Sets - SVG 1.1 - 20030114" value="https://www.w3.org/TR/SVG/feature.html"> <option label="The Single UNIX Specification, Version 3" value="https://www.unix-systems.org/version3/"> </datalist>
...and the user had typed "www.w3", and the user agent had also found that the user
had visited https://www.w3.org/Consortium/#membership
and https://www.w3.org/TR/XForms/
in the recent past, then the rendering might look
like this:
The first four URLs in this sample consist of the four URLs in the author-specified list that match the text the user has entered, sorted in some user agent-defined manner (maybe by how frequently the user refers to those URLs). Note how the user agent is using the knowledge that the values are URLs to allow the user to omit the scheme part and perform intelligent matching on the domain name.
The last two URLs (and probably many more, given the scrollbar’s indications of more values being available) are the matches from the user agent’s session history data. This data is not made available to the page DOM. In this particular case, the user agent has no titles to provide for those values.
4.10.5.1.5. E-mail state (type=email
)
- Allowed ARIA role attribute values:
textbox
with nolist
attribute (default - do not set) or with alist
attribute:combobox
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the E-mail
state, the rules in this section apply.
User agents may transform the values for display and editing.
User agents should convert punycode in the domain labels of the value to Internationalized Domain Names in the display, and vice versa.
User agents should allow the user to set the value to a string that is not a valid e-mail address or valid e-mail address list.
User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the value.
Some aspects of how the E-mail
state operates depend on whether the multiple
attribute is present.
- When the
multiple
attribute is not specified on the element -
The
input
element represents a control for editing an e-mail address given in the element’s value.If the element is mutable, the user agent should allow the user to change the e-mail address represented by its value, including setting the value to the empty string.
The user agent should act in a manner consistent with expecting the user to provide a single e-mail address.
Constraint validation: While the user interface is representing input that the user agent cannot convert to punycode, the control is suffering from bad input.
The
value
attribute, if specified and not empty, must have a value that is a single valid e-mail address.The value sanitization algorithm is as follows: Strip line breaks from the value, then strip leading and trailing white space from the value.
Constraint validation: While the value of the element is neither the empty string nor a single valid e-mail address, the element is suffering from a type mismatch.
- When the
multiple
attribute is specified on the element -
The
input
element represents a control for adding, removing, and editing a list of e-mail addresses given in the element’s values.If the element is mutable, the user agent should allow the user to add, remove, and edit the e-mail addresses represented by its values, including removing all addresses and setting the value to the empty string.
User agents may allow the user to set any individual value in the list of values to a string that is not a valid e-mail address, but must not allow users to set any individual value to a string containing U+002C COMMA (,) as well as the U+000A LINE FEED (LF), or U+000D CARRIAGE RETURN (CR) characters.
Constraint validation: While the user interface describes a situation where an individual value contains a U+002C COMMA (,) or is representing input that the user agent cannot convert to punycode, the control is suffering from bad input.
Whenever the user changes the element’s values, the user agent must run the following steps:
- Let latest values be a copy of the element’s values.
- Strip leading and trailing white space from each value in latest values.
- Let the element’s value be the result of concatenating all the values in latest values, separating each value from the next by a single U+002C COMMA character (,), maintaining the list’s order.
The
value
attribute, if specified, must have a value that is a valid e-mail address list.The value sanitization algorithm is as follows:
- Split on commas the element’s value, strip leading and trailing white space from each resulting token, if any, and let the element’s values be the (possibly empty) resulting list of (possibly empty) tokens, maintaining the original order.
- Let the element’s value be the result of concatenating the element’s values, separating each value from the next by a single U+002C COMMA character (,), maintaining the list’s order.
Constraint validation: While the value of the element is not a valid e-mail address list, the element is suffering from a type mismatch.
When the multiple
attribute is set or removed, the
user agent must run the value sanitization algorithm.
A valid e-mail address is a string that matches the email
production of the following ABNF, the character set for which is Unicode. This ABNF implements the
extensions described in RFC 1123. [ABNF] [RFC5322] [RFC1034] [RFC1123]
email = 1*( atext / "." ) "@" label *( "." label ) label = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 characters by RFC 1034 section 3.5 atext = ALPHA / DIGIT / ; Printable US-ASCII characters not including "specials". "!" / "#" / ; "$" / "%" / ; This is as defined in RFC 5322 section 3.2.3 "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" let-dig = ALPHA / DIGIT ; defined in RFC 1034 section 3.5 ldh-str = let-dig / "-" ; defined in RFC 1034 section 3.5
This requirement is a willful violation of RFC 5322.
This syntax allows e-mail addresses with Internationalised Domain Names using punycode, such as example@xn--d1acpjx3f.xn--p1ai
. A user agent should represent that in the user interface
as example@яндекс.рф
This syntax does not allow valid internationalised email addresses, such as 我買@屋企.香港. See also Issue 845.
The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
A valid e-mail address list is a set of comma-separated tokens, where each token is itself a valid e-mail address. To obtain the list of tokens from a valid e-mail address list, an implementation must split the string on commas.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, maxlength
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, and size
content attributes; list
and value
IDL attributes; select()
method.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, max
, min
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
and stepUp()
methods.
4.10.5.1.6. Password state (type=password
)
When an input
element’s type
attribute is in
the Password state, the rules in this section
apply.
The input
element represents a one line plain text edit control for
the element’s value. The user agent should obscure the value
so that people other than the user cannot see it.
If the element is mutable, its value should be editable by the user. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the value.
The value
attribute, if specified, must have a value that
contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
The value sanitization algorithm is as follows: Strip line breaks from the value.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, inputmode
, maxlength
, minlength
, pattern
, placeholder
, readonly
, required
, and size
content attributes; selectionStart
, selectionEnd
, selectionDirection
, and value
IDL attributes; select()
, setRangeText()
, and setSelectionRange()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, list
, max
, min
, multiple
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, list
, valueAsDate
, and valueAsNumber
IDL attributes; stepDown()
and stepUp()
methods.
4.10.5.1.7. Date and Time state (type=datetime
)
When an input
element’s type
attribute is in
the Date and Time
state, the rules in this section
apply.
The input
element represents a control for setting the element’s value to a string representing a specific global date and time.
User agents may display the date and time in whatever time zone is appropriate for the user.
If the element is mutable, the user agent should allow the user to change the global date and time represented by its value, as obtained by parsing a floating date and time from it. User agents must not allow the user to set the value to a non-empty string that is not a valid normalized global date and time string, though user agents may allow the user to set and view the time in another time zone and silently translate the time to and from the UTC time zone in the value. If the user agent provides a user interface for selecting a global date and time, then the value must be set to a valid normalized global date and time string representing the user’s selection. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid normalized global date and time string, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid global date and time string.
The value sanitization algorithm is as follows: If the value of the element is a valid global date and time string, then adjust the time so that the value represents the same point in time but expressed in the UTC time zone as a valid normalized global date and time string, otherwise, set it to the empty string instead.
The min
attribute, if specified, must have a value that is
a valid global date and time string. The max
attribute, if specified, must have a value that is a valid global date and time
string.
The step
attribute is expressed in seconds. The step scale factor is 1000 (which
converts the seconds to milliseconds, which is the base unit of comparison for the conversion
algorithms below). The default step is 60 seconds.
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest global date and time for which the element would not suffer from a step mismatch.
The algorithm to convert a string to a
number, given a string input, is as follows: If parsing a floating date and time from input results in an error, then return an error; otherwise, return the number of
milliseconds elapsed from midnight UTC on the morning of 1970-01-01 (the time represented by the
value "1970-01-01T00:00:00.0Z
") to the parsed global date and time, ignoring leap seconds.
The algorithm to convert a number to a
string, given a number input, is as follows: Return a valid normalized global date and time string that represents the global date and time that is input milliseconds after midnight UTC on the morning of 1970-01-01 (the time represented by the value
"1970-01-01T00:00:00.0Z
").
The algorithm to convert a string to a Date
object, given a string input, is as follows:
If parsing a floating date and time from input results in an error, then return an error; otherwise, return a new Date
object representing the parsed global date and time, expressed in UTC.
The algorithm to convert a Date
object to a string, given a Date
object input, is as follows: Return a valid normalized global date and time string that represents the global date and
time that is represented by input.
The Date and Time
state (and other date-related states are not
useful for vague values, and are only useful for dates ranging from recent history through a
few thousand years. For example, "one millisecond after the big bang", "the Ides of March, 44BC",
"the early part of the Jurassic period", or "a winter around 250 BCE", and many other expressions
of time cannot be sensibly expressed in HTML form
states.
For the input of dates before the introduction of the Gregorian calendar, authors are
encouraged to not use the Date and Time
state (and
the other date- and time-related states described in subsequent sections), as user agents are not
required to support converting dates and times from earlier periods to the Gregorian calendar,
and asking users to do so manually puts an undue burden on users. (This is complicated by the
manner in which the Gregorian calendar was phased in, which occurred at different times in
different countries, ranging from partway through the 16th century all the way to early in the
20th.) Instead, authors are encouraged to provide fine-grained input controls using the select
element and input
elements with the Number
state.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, max
, min
, readonly
, required
, and step
content attributes; list
, value
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, placeholder
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, selectionStart
, selectionEnd
, and selectionDirection
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
<fieldset> <legend>Add Meeting</legend> <p><label>Meeting name: <input type=text name="meeting.label"></label> <p><label>Meeting time: <input type=datetime name="meeting.start"></label> </fieldset>
Had the application used the date
and/or time
types instead, the calendar application would
have also had to explicitly determine which time zone the user intended.
For events where the precise time is to vary as the user travels (e.g., "celebrate the new
year!"), and for recurring events that are to stay at the same time for a specific geographic
location even though that location may go in and out of daylight savings time (e.g., "bring the
kid to school"), the date
and/or time
types combined with a select
element
(or other similar control) to pick the specific geographic location to which to anchor the time
would be more appropriate.
4.10.5.1.8. Date state (type=date
)
When an input
element’s type
attribute is in
the Date
state, the rules in this section apply.
The input
element represents a control for setting the element’s value to a string representing a specific date.
date values represent a "floating" time and do not include time zone information. Care is needed when converting values of this type to or from date data types in JavaScript and other programming languages. In many cases, an implicit time-of-day and time zone are used to create a global ("incremental") time (an integer value that represents the offset from some arbitrary epoch time). Processing or conversion of these values, particularly across time zones, can change the value of the date itself. [TIMEZONE]
If the element is mutable, the user agent should allow the user to change the date represented by its value, as obtained by parsing a date from it. User agents must not allow the user to set the value to a non-empty string that is not a valid date string. If the user agent provides a user interface for selecting a date, then the value must be set to a valid date string representing the user’s selection. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid date string, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid date string.
The value sanitization algorithm is as follows: If the value of the element is not a valid date string, then set it to the empty string instead.
The min
attribute, if specified, must have a value that is
a valid date string. The max
attribute, if
specified, must have a value that is a valid date string.
The step
attribute is expressed in days. The step scale factor is 86,400,000 (which converts the days to milliseconds, which is the base unit of comparison for
the conversion algorithms below). The default step is 1 day.
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest date for which the element would not suffer from a step mismatch.
The algorithm to convert a string to a
number, given a string input, is as follows: If parsing a date from input results in an
error, then return an error; otherwise, return the number of milliseconds elapsed from midnight
UTC on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z
") to midnight UTC on the morning of the parsed date, ignoring leap seconds.
The algorithm to convert a number to a
string, given a number input, is as follows: Return a valid date string that represents the date that, in
UTC, is current input milliseconds after midnight UTC on the morning of
1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z
").
The algorithm to convert a string to a Date
object, given a string input, is as follows:
If parsing a date from input results
in an error, then return an error; otherwise, return a new Date
object representing midnight UTC on the morning of the parsed date.
The algorithm to convert a Date
object to a string, given a Date
object input, is as follows: Return a valid date string that
represents the date current at the time represented by input in the UTC time zone.
See the note on historical dates in the Date and Time
state section.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, max
, min
, readonly
, required
, and step
content attributes; list
, value
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, placeholder
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, selectionStart
, selectionEnd
, and selectionDirection
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
4.10.5.1.9. Month state (type=month
)
When an input
element’s type
attribute is in
the Month state, the rules in this section apply.
The input
element represents a control for setting the element’s value to a string representing a specific month.
If the element is mutable, the user agent should allow the user to change the month represented by its value, as obtained by parsing a month from it. User agents must not allow the user to set the value to a non-empty string that is not a valid month string. If the user agent provides a user interface for selecting a month, then the value must be set to a valid month string representing the user’s selection. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid month string, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid month string.
The value sanitization algorithm is as follows: If the value of the element is not a valid month string, then set it to the empty string instead.
The min
attribute, if specified, must have a value that is
a valid month string. The max
attribute, if
specified, must have a value that is a valid month string.
The step
attribute is expressed in months. The step scale factor is 1
(units of whole months are the base unit of comparison for the conversion algorithms below).
The default step is 1 month.
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest month for which the element would not suffer from a step mismatch.
The algorithm to convert a string to a number, given a string input, is as follows: If parsing a month from input results in an error, then return an error; otherwise, return the number of months between January 1970 and the parsed month.
The algorithm to convert a number to a string, given a number input, is as follows: Return a valid month string that represents the month that has input months between it and January 1970.
The algorithm to convert a string to a Date
object, given a string input, is as follows:
If parsing a month from input results in an error, then return an error; otherwise, return a
new Date
object representing midnight UTC on the morning of the first day of
the parsed month.
The algorithm to convert a Date
object to a string,
given a Date
object input, is as follows:
Return a valid month string that
represents the month current at the time represented by input in the UTC time zone.
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, max
, min
, readonly
, required
, and step
content attributes; list
, value
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, placeholder
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, selectionStart
, selectionEnd
, and selectionDirection
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
4.10.5.1.10. Week state (type=week
)
When an input
element’s type
attribute is in
the Week state, the rules in this section apply.
The input
element represents a control for setting the element’s value to a string representing a specific week beginning on a Monday, at midnight UTC.
If the element is mutable, the user agent should allow the user to change the week represented by its value, as obtained by parsing a week from it. User agents must not allow the user to set the value to a non-empty string that is not a valid week string. If the user agent provides a user interface for selecting a week, then the value must be set to a valid week string representing the user’s selection. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid week string, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid week string.
The value sanitization algorithm is as follows: If the value of the element is not a valid week string, then set it to the empty string instead.
The min
attribute, if specified, must have a value that is
a valid week string. The max
attribute, if
specified, must have a value that is a valid week string.
The step
attribute is expressed in weeks. The step scale factor is 604,800,000
(which converts the weeks to milliseconds, which is the base unit of comparison for the conversion
algorithms below). The default step is 1 week. The default step base is -259,200,000
(the start of week 1970-W01 which is the Monday 3 days before 1970-01-01).
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest week for which the element would not suffer from a step mismatch.
The algorithm to convert a string to a
number, given a string input, is as follows: If parsing a week string from input results in
an error, then return an error; otherwise, return the number of milliseconds elapsed from midnight
UTC on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z
") to midnight UTC on the morning of the Monday of the
parsed week, ignoring leap seconds.
The algorithm to convert a number to a
string, given a number input, is as follows: Return a valid week string that represents the week that, in
UTC, is current input milliseconds after midnight UTC on the morning of
1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z
").
The algorithm to convert a string to a Date
object, given a string input, is as follows:
If parsing a week from input results
in an error, then return an error; otherwise, return a new Date
object representing midnight UTC on the morning of the Monday of the
parsed week.
The algorithm to convert a Date
object to a string, given a Date
object input, is as follows: Return a valid week string that
represents the week current at the time represented by input in the UTC time zone.
The following common input
element content attributes, IDL attributes, and
methods apply to the element: autocomplete
, list
, max
, min
, readonly
, required
, and step
content attributes; list
, value
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, placeholder
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, selectionStart
, selectionEnd
, and selectionDirection
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
4.10.5.1.11. Time state (type=time
)
When an input
element’s type
attribute is in
the Time state, the rules in this section apply.
The input
element represents a control for setting the element’s value to a string representing a specific time.
If the element is mutable, the user agent should allow the user to change the time represented by its value, as obtained by parsing a time from it. User agents must not allow the user to set the value to a non-empty string that is not a valid time string. If the user agent provides a user interface for selecting a time, then the value must be set to a valid time string representing the user’s selection. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid time string, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid time string.
The value sanitization algorithm is as follows: If the value of the element is not a valid time string, then set it to the empty string instead.
The form control has a periodic domain.
The min
attribute, if specified, must have a value that is
a valid time string. The max
attribute, if
specified, must have a value that is a valid time string.
The step
attribute is expressed in seconds. The step scale factor is 1000
(which converts the seconds to milliseconds, which is the base unit of comparison for the
conversion algorithms below). The default step is 60 seconds.
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest time for which the element would not suffer from a step mismatch.
The algorithm to convert a string to a number, given a string input, is as follows: If parsing a time from input results in an error, then return an error; otherwise, return the number of milliseconds elapsed from midnight to the parsed time on a day with no time changes.
The algorithm to convert a number to a string, given a number input, is as follows: Return a valid time string that represents the time that is input milliseconds after midnight on a day with no time changes.
The algorithm to convert a string to a Date
object, given a string input, is as follows:
If parsing a time from input results
in an error, then return an error; otherwise, return a new Date
object representing the parsed time in
UTC on 1970-01-01.
The algorithm to convert a Date
object to a string, given a Date
object input, is as follows: Return a valid time string that
represents the UTC time component that is represented by input.
The following common input
element content attributes, IDL attributes, and
methods apply to the element: autocomplete
, list
, max
, min
, readonly
, required
, and step
content attributes; list
, value
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, placeholder
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, selectionStart
, selectionEnd
, and selectionDirection
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
4.10.5.1.12. Local Date and Time state (type=datetime-local
)
When an input
element’s type
attribute is in
the Local Date and Time
state, the rules in
this section apply.
The input
element represents a control for setting the element’s value to a string representing a Local Date and Time
,
with no time-zone offset information.
If the element is mutable, the user agent should allow the
user to change the Date and Time
represented by its value, as obtained by parsing a date and time from it.
User agents must not allow the user to set the value to a non-empty string
that is not a valid normalized global date and time string.
If the user agent provides a user interface for selecting a Local Date and Time
,
then the value must be set to a valid normalized global date and time string representing the user’s selection. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid normalized global date and time string, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid floating date and time string.
The value sanitization algorithm is as follows: If the value of the element is a valid floating date and time string, then set it to a valid normalized floating date and time string representing the same date and time; otherwise, set it to the empty string instead.
The min
attribute, if specified, must have a value that is
a valid floating date and time string. The max
attribute, if specified, must have a value that is a valid floating date and time string.
The step
attribute is expressed in seconds. The step scale factor is 1000
(which converts the seconds to milliseconds, which is the base unit of comparison for the
conversion algorithms below). The default step is 60 seconds.
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest floating date and time for which the element would not suffer from a step mismatch.
The algorithm to convert a string to a
number, given a string input, is as follows: If parsing a date and time from input results in an error, then return an error; otherwise, return the number of
milliseconds elapsed from midnight on the morning of 1970-01-01 (the time represented by the value
"1970-01-01T00:00:00.0
") to the parsed floating date and time, ignoring leap seconds.
The algorithm to convert a number to a
string, given a number input, is as follows: Return a valid normalized floating date and time string that represents the date and time that is input milliseconds after midnight on the morning of 1970-01-01 (the time
represented by the value "1970-01-01T00:00:00.0
").
See the note on historical dates in the Date and Time
state section.
Applications need to use care when working with datetime-local
values,
since most date time objects (in languages such as JavaScript or server-side languages such as Java) use
incremental time values tied to the UTC time zone. Implicit conversion of a floating time value to an incremental
time can cause the actual value used to be different from user expectations.
For more information, refer to: Working with Time Zones §floating
The following common input
element content
attributes, IDL attributes, and methods apply to the element: autocomplete
, list
, max
, min
, readonly
, required
, and step
content attributes; list
, value
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is
in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not
apply to the element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, placeholder
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the
element: checked
, files
, selectionStart
, selectionEnd
, selectionDirection
, and valueAsDate
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
input
element with its type
attribute set to datetime-local
, and it then interprets the
given date and time in the time zone of the selected airport.
<fieldset> <legend>Destination</legend> <p><label>Airport: <input type=text name=to list=airports></label></p> <p><label>Departure time: <input type=datetime-local name=totime step=3600></label></p> </fieldset> <datalist id=airports> <option value=ATL label="Atlanta"> <option value=MEM label="Memphis"> <option value=LHR label="London Heathrow"> <option value=LAX label="Los Angeles"> <option value=FRA label="Frankfurt"> </datalist>
If the application instead used the datetime
type, then the user would have to work out the time-zone conversions themself, which is clearly
not a good user experience!
4.10.5.1.13. Number state (type=number
)
- Allowed ARIA role attribute values:
spinbutton
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Number
state, the rules in this section apply.
The input
element represents a control for setting the element’s value to a string representing a number.
If the element is mutable, the user agent should allow the user to change the number represented by its value, as obtained from applying the rules for parsing floating-point number values to it. User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number. If the user agent provides a user interface for selecting a number, then the value must be set to the best representation of the number representing the user’s selection as a floating-point number. User agents should allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid floating-point number, the control is suffering from bad input.
See §4.10.1.8 Date, time, and number formats for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.
The value
attribute, if specified and not empty, must
have a value that is a valid floating-point number.
The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.
The min
attribute, if specified, must have a value that is
a valid floating-point number. The max
attribute,
if specified, must have a value that is a valid floating-point number.
The step scale factor is 1. The default step is 1 (allowing only integers to be selected by the user, unless the step base has a non-integer value).
When the element is suffering from a step mismatch, the user agent may round the element’s value to the nearest number for which the element would not suffer from a step mismatch. If there are two such numbers, user agents are encouraged to pick the one nearest positive infinity.
The algorithm to convert a string to a number, given a string input, is as follows: If applying the rules for parsing floating-point number values to input results in an error, then return an error; otherwise, return the resulting number.
The algorithm to convert a number to a string, given a number input, is as follows: Return a valid floating-point number that represents input.
The following common input
element content attributes, IDL attributes, and
methods apply to the element: autocomplete
, list
, max
, min
, placeholder
, readonly
, required
, and step
content attributes; list
, value
, and valueAsNumber
IDL attributes; select()
, stepDown()
, and stepUp()
methods.
The value
IDL attribute is in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, multiple
, pattern
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, selectionStart
, selectionEnd
, selectionDirection
, and valueAsDate
IDL attributes; setRangeText()
, and setSelectionRange()
methods.
<label>How much do you want to charge? $<input type=number min=0 step=0.01 name=price></label>
As described above, a user agent might support numeric input in the user’s local format, converting it to the format required for submission as described above. This might include handling grouping separators (as in "872,000,000,000") and various decimal separators (such as "3,99" vs "3.99") or using local digits (such as those in Arabic, Devanagari, Persian, and Thai).
The type=number
state is not appropriate for input that
happens to only consist of numbers but isn’t strictly speaking a number. For example, it would be
inappropriate for credit card numbers or US postal codes. A simple way of determining whether to
use type=number
is to consider whether it would make sense for the input
control to have a spinbox interface (e.g., with "up" and "down" arrows). Getting a credit card
number wrong by 1 in the last digit isn’t a minor mistake, it’s as wrong as getting every digit
incorrect. So it would not make sense for the user to select a credit card number using "up" and
"down" buttons. When a spinbox interface is not appropriate, type=text
is
probably the right choice (possibly with a pattern
attribute).
4.10.5.1.14. Range state (type=range
)
- Allowed ARIA role attribute values:
-
slider
(default - do not set). - Allowed ARIA state and property attributes:
-
Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in the Range
state, the rules in this section apply.
The input
element represents a control for setting the element’s value to a string representing a number, but with the caveat that the exact
value is not important, letting user agents provide a simpler interface than they do for the Number
state.
If the element is mutable, the user agent should allow the user to change the number represented by its value, as obtained from applying the rules for parsing floating-point number values to it. User agents must not allow the user to set the value to a string that is not a valid floating-point number. If the user agent provides a user interface for selecting a number, then the value must be set to a best representation of the number representing the user’s selection as a floating-point number. User agents must not allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid floating-point number, the control is suffering from bad input.
The value
attribute, if specified, must have a value that is a valid floating-point number.
The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the best representation, as a floating-point number, of the default value.
The default value is the minimum plus half the difference between the minimum and the maximum, unless the maximum is less than the minimum, in which case the default value is the minimum.
When the element is suffering from an underflow, the user agent must set the element’s value to the best representation, as a floating-point number, of the minimum.
When the element is suffering from an overflow, if the maximum is not less than the minimum, the user agent must set the element’s value to a valid floating-point number that represents the maximum.
When the element is suffering from a step mismatch, the user agent must round the element’s value to the nearest number for which the element would not suffer from a step mismatch, and which is greater than or equal to the minimum, and, if the maximum is not less than the minimum, which is less than or equal to the maximum, if there is a number that matches these constraints. If two numbers match these constraints, then user agents must use the one nearest to positive infinity.
For example, the markup <input type="range" min=0 max=100 step=20 value=50>
results in a range control whose initial value is 60.
list
attribute. This could be useful if there are values along the full range of the control that are
especially important, such as preconfigured light levels or typical speed limits in a range
control used as a speed control. The following markup fragment:
<input type="range" min="-100" max="100" value="0" step="10" name="power" list="powers"> <datalist id="powers"> <option value="0"> <option value="-30"> <option value="30"> <option value="++50"> </datalist>
...with the following style sheet applied:
input { height: 75px; width: 49px; background: #D5CCBB; color: black; }
...might render as:
Note how the user agent determined the orientation of the control from the ratio of the
style-sheet-specified height and width properties. The colors were similarly derived from the
style sheet. The tick marks, however, were derived from the markup. In particular, the step
attribute has not affected the placement of tick marks, the user agent deciding
to only use the author-specified completion values and then adding longer tick marks at the
extremes.
Note also how the invalid value ++50
was completely ignored.
<input name=x type=range min=100 max=700 step=9.09090909 value=509.090909>
A user agent could display in a variety of ways, for instance:
Or, alternatively, for instance:
The user agent could pick which one to display based on the dimensions given in the style sheet. This would allow it to maintain the same resolution for the tick marks, despite the differences in width.
<input type="range" name="a" list="a-values"> <datalist id="a-values"> <option value="10" label="Low"> <option value="90" label="High"> </datalist>
With styles that make the control draw vertically, it might look as follows:
In this state, the range and step constraints are enforced even during user input, and there is no way to set the value to the empty string.
The min
attribute, if specified, must have a value that is a valid floating-point number. The default minimum is 0. The max
attribute,
if specified, must have a value that is a valid floating-point number. The default maximum is 100.
The step scale factor is 1. The default step is 1 (allowing only integers, unless
the min
attribute has a non-integer value).
The algorithm to convert a string to a number, given a string input, is as follows: If applying the rules for parsing floating-point number values to input results in an error, then return an error; otherwise, return the resulting number.
The algorithm to convert a number to a string, given a number input, is as follows: Return the best representation, as a floating-point number, of input.
input
element content attributes, IDL attributes, and
methods apply to the element: autocomplete
, list
, max
, min
, multiple
, and step
content attributes; list
, value
, and valueAsNumber
IDL attributes; stepDown()
and stepUp()
methods.
The value
IDL attribute is in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, maxlength
, minlength
, pattern
, placeholder
, readonly
, required
, size
, src
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, selectionStart
, selectionEnd
, selectionDirection
, and valueAsDate
IDL attributes; select()
, setRangeText()
, and setSelectionRange()
methods.
4.10.5.1.15. Color state (type=color
)
When an input
element’s type
attribute is in
the Color
state, the rules in this section apply.
The input
element represents a color well control, for setting the
element’s value to a string representing a simple
color.
In this state, there is always a color picked, and there is no way to set the value to the empty string.
If the element is mutable, the user agent should allow the user to change the color represented by its value, as obtained from applying the rules for parsing simple color values to it. User agents must not allow the user to set the value to a string that is not a valid lowercase simple color. If the user agent provides a user interface for selecting a color, then the value must be set to the result of using the rules for serializing simple color values to the user’s selection. User agents must not allow the user to set the value to the empty string.
Constraint validation: While the user interface describes input that the user agent cannot convert to a valid lowercase simple color, the control is suffering from bad input.
The value
attribute, if specified and not empty, must
have a value that is a valid simple color.
The value sanitization algorithm is as follows: If the value of the element is a valid simple color, then set it to the value of the element in ASCII lowercase; otherwise, set it to
the string "#000000
".
The following common input
element content attributes and IDL attributes apply to the
element: autocomplete
and list
content attributes; list
and value
IDL attributes; select()
method.
The value
IDL attribute is in mode value.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
4.10.5.1.16. Checkbox state (type=checkbox
)
- Allowed ARIA role attribute values:
checkbox
(default - do not set),menuitemcheckbox
,option
orswitch
.- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Checkbox
state, the rules in this section
apply.
The input
element represents a two-state control that represents the
element’s checkedness state. If the element’s checkedness state is true, the control represents a positive
selection, and if it is false, a negative selection. If the element’s indeterminate
IDL attribute is set to true, then the
control’s selection should be obscured as if the control was in a third, indeterminate, state.
The control is never a true tri-state control, even if the element’s indeterminate
IDL attribute is set to true. The indeterminate
IDL attribute only gives the appearance of a
third state.
If the element is mutable, then: The pre-click
activation steps consist of setting the element’s checkedness to its opposite value (i.e., true if it is false,
false if it is true), and of setting the element’s indeterminate
IDL attribute to false. The canceled
activation steps consist of setting the checkedness and the element’s indeterminate
IDL attribute back to the values they had
before the pre-click activation steps were run. The activation behavior is to fire a simple event that bubbles named input
at the element and then fire a simple event that bubbles named change
at the element.
If the element is not mutable, it has no activation behavior.
Constraint validation: If the element is required and its checkedness is false, then the element is suffering from being missing.
- input .
indeterminate
[ = value ] -
When set, overrides the rendering of
checkbox
controls so that the current value is not visible.
The following common input
element content attributes and IDL attributes apply to the element: checked
, and required
content attributes; checked
and value
IDL attributes.
The value
IDL attribute is in mode default/on.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, autocomplete
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the element: files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
4.10.5.1.17. Radio Button state (type=radio
)
- Allowed ARIA role attribute values:
radio
(default - do not set) ormenuitemradio
.- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Radio Button
state, the rules in this section
apply.
The input
element represents a control that, when used in conjunction
with other input
elements, forms a radio button group in which only one
control can have its checkedness state set to true. If
the element’s checkedness state is true, the control
represents the selected control in the group, and if it is false, it indicates a control in the
group that is not selected.
The radio button group that contains an input
element a also contains all the other input
elements b that fulfill all
of the following conditions:
- The
input
element b’stype
attribute is in theRadio Button
state. - Either a and b have the same form owner, or they both have no form owner.
- Both a and b are in the same tree.
- They both have a
name
attribute, theirname
attributes are not empty, and the value of a’sname
attribute is a compatibility caseless match for the value of b’sname
attribute.
A document must not contain an input
element whose radio button group contains only that element.
When any of the following phenomena occur, if the element’s checkedness state is true after the occurrence, the checkedness state of all the other elements in the same radio button group must be set to false:
- The element’s checkedness state is set to true (for whatever reason).
- The element’s
name
attribute is set, changed, or removed. - The element’s form owner changes.
- A type change is signalled for the element.
If the element R is mutable, then: The pre-click activation steps for R consist of getting a reference to the
element in R’s radio button group that has its checkedness set to true, if any, and then setting R’s checkedness to true. The canceled
activation steps for R consist of checking if the element to which a reference
was obtained in the pre-click activation steps, if any, is still in what is now R’s radio button group, if it still has one, and if so, setting that
element’s checkedness to true; or else, if there was no
such element, or that element is no longer in R’s radio button group, or
if R no longer has a radio button group, setting R’s checkedness to false. The activation behavior for R is to fire a simple event that bubbles named input
at R and then fire a simple event that bubbles named change
at R.
If the element is not mutable, it has no activation behavior.
Constraint validation: If an element in the radio button group is required, and all of the input
elements in the radio button group have a checkedness that is
false, then the element is suffering from being missing.
If none of the radio buttons in a radio button group are checked when they are inserted into the document, then they will all be initially unchecked in the interface, until such time as one of them is checked (either by the user or by script).
The following common input
element content attributes and IDL attributes apply to the element: checked
and required
content attributes; checked
and value
IDL attributes.
The value
IDL attribute is in mode default/on.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, autocomplete
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the element: files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
4.10.5.1.18. File Upload state (type=file
)
When an input
element’s type
attribute is in
the File Upload
state, the rules in this section
apply.
The input
element represents a list of selected files, each file consisting of a file
name, a file type, and a file body (the contents of the file).
File names must not contain path components, even
in the case that a user has selected an entire directory hierarchy or multiple files with the same
name from different directories. Path components, for
the purposes of the File Upload
state, are those parts
of file names that are separated by U+005C REVERSE SOLIDUS character (\) characters.
Unless the multiple
attribute is set, there must be
no more than one file in the list of selected
files.
If the element is mutable, then the element’s activation behavior is to run the following steps:
- If the algorithm is not allowed to show a popup, then abort these steps without doing anything else.
- Return, but continue running these steps in parallel.
- Optionally, wait until any prior execution of this algorithm has terminated.
- Display a prompt to the user requesting that the user specify some files. If the
multiple
attribute is not set, there must be no more than one file selected; otherwise, any number may be selected. Files can be from the filesystem or created on the fly, e.g., a picture taken from a camera connected to the user’s device. - Wait for the user to have made their selection.
- Queue a task to first update the element’s selected files so that it represents the user’s
selection, then fire a simple event that bubbles named
input
at theinput
element, and finally fire a simple event that bubbles namedchange
at theinput
element.
If the element is mutable, the user agent should allow the
user to change the files on the list in other ways also, e.g., adding or removing files by
drag-and-drop. When the user does so, the user agent must queue a task to first
update the element’s selected files so that
it represents the user’s new selection, then fire a simple event that bubbles named input
at the input
element, and finally fire a simple event that bubbles named change
at the input
element.
If the element is not mutable, it has no activation behavior and the user agent must not allow the user to change the element’s selection.
Constraint validation: If the element is required and the list of selected files is empty, then the element is suffering from being missing.
The accept
attribute may be specified to
provide user agents with a hint of what file types will be accepted.
If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:
- The string "
audio/*
" - Indicates that sound files are accepted.
- The string "
video/*
" - Indicates that video files are accepted.
- The string "
image/*
" - Indicates that image files are accepted.
- A valid MIME type with no parameters
- Indicates that files of the specified type are accepted.
- A string whose first character is a U+002E FULL STOP character (.)
- Indicates that files with the specified file extension are accepted.
The tokens must not be ASCII case-insensitive matches for any of the other tokens (i.e., duplicates are not allowed). To obtain the list of tokens from the attribute, the user agent must split the attribute value on commas.
User agents may use the value of this attribute to display a more appropriate user interface
than a generic file picker. For instance, given the value image/*
, a user
agent could offer the user the option of using a local camera or selecting a photograph from their
photo collection; given the value audio/*
, a user agent could offer the user
the option of recording a clip using a headset microphone.
User agents should prevent the user from selecting files that are not accepted by one (or more) of these tokens.
Authors are encouraged to specify both any MIME types and any corresponding extensions when looking for data in a specific format.
<input type="file" accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
On platforms that only use file extensions to describe file types, the extensions listed here can be used to filter the allowed documents, while the MIME types can be used with the system’s type registration table (mapping MIME types to extensions used by the system), if any, to determine any other extensions to allow. Similarly, on a system that does not have file names or extensions but labels documents with MIME types internally, the MIME types can be used to pick the allowed files, while the extensions can be used if the system has an extension registration table that maps known extensions to MIME types used by the system.
Extensions tend to be ambiguous (e.g., there are an untold number of formats
that use the ".dat
" extension, and users can typically quite easily rename
their files to have a ".doc
" extension even if they are not Microsoft Word
documents), and MIME types tend to be unreliable (e.g., many formats have no formally registered
types, and many formats are in practice labeled using a number of different MIME types). Authors
are reminded that, as usual, data received from a client should be treated with caution, as it may
not be in an expected format even if the user is not hostile and the user agent fully obeyed the accept
attribute’s requirements.
value
IDL attribute prefixes
the file name with the string "C:\fakepath\
". Some legacy user agents
actually included the full path (which was a security vulnerability). As a result of this,
obtaining the file name from the value
IDL attribute in a
backwards-compatible way is non-trivial. The following function extracts the file name in a
suitably compatible manner:
function extractFilename(path) { if (path.substr(0, 12) == "C:\\fakepath\\") return path.substr(12); // modern browser var x; x = path.lastIndexOf('/'); if (x >= 0) // Unix-based path return path.substr(x+1); x = path.lastIndexOf('\\'); if (x >= 0) // Windows-based path return path.substr(x+1); return path; // just the file name }
This can be used as follows:
<p><input type=file name=image onchange="updateFilename(this.value)"></p> <p>The name of the file you picked is: <span id="filename">(none)</span></p> <script> function updateFilename(path) { var name = extractFilename(path); document.getElementById('filename').textContent = name; } </script>
input
element content attributes and IDL attributes apply to the element: accept
, multiple
, and required
content attributes; files
and value
IDL attributes; select()
method.
The value
IDL attribute is in mode filename.
The input
and change
events apply.
The following content attributes must not be specified and do not apply to the
element: alt
, autocomplete
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, pattern
, placeholder
, readonly
, size
, src
, step
, and width
.
The element’s value
attribute must be omitted.
The following IDL attributes and methods do not apply to the element: checked
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
4.10.5.1.19. Submit Button state (type=submit
)
- Allowed ARIA role attribute values:
button
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Submit Button
state, the rules in this section
apply.
The input
element represents a button that, when activated, submits
the form. If the element has a value
attribute,
the button’s label must be the value of that attribute;
otherwise, it must be an implementation-defined string that means "Submit" or some such.
The element is a button, specifically a submit button.
Since the default label is implementation-defined, and the width of the button typically depends on the button’s label, the button’s width can leak a few bits of fingerprintable information. These bits are likely to be strongly correlated to the identity of the user agent and the user’s locale.
If the element is mutable, then the element’s activation behavior is as follows: if the element has a form owner,
and the element’s node document is fully active, submit the form owner from the input
element; otherwise, do nothing.
If the element is not mutable, it has no activation behavior.
The formaction
, formenctype
, formmethod
, formnovalidate
, and formtarget
attributes are attributes for form
submission.
The formnovalidate
attribute can be
used to make submit buttons that do not trigger the constraint validation.
The following common input
element content attributes and IDL attributes apply to the element: formaction
, formenctype
, formmethod
, formnovalidate
, and formtarget
content attributes; value
IDL attribute.
The value
IDL attribute is in mode default.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, autocomplete
, checked
, dirname
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
The input
and change
events do not apply.
4.10.5.1.20. Image Button state (type=image
)
- Allowed ARIA role attribute values:
button
(default - do not set),link
,menuitem
,menuitemcheckbox
,menuitemradio
orradio
.- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Image Button
state, the rules in this section
apply.
The input
element represents either an image from which a user can
select a coordinate and submit the form, or alternatively a button from which the user can submit
the form. The element is a button, specifically a Submit Button
.
The coordinate is sent to the server during form submission by sending two entries for the element, derived from the name
of the control but with ".x
" and ".y
" appended to the
name with the x and y components of the coordinate
respectively.
The image is given by the src
attribute. The src
attribute must be present, and must contain a valid
non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally
animated, image resource that is neither paged nor scripted.
When any of the these events occur
- the
input
element’stype
attribute is first set to theImage Button
state (possibly when the element is first created), and thesrc
attribute is present - the
input
element’stype
attribute is changed back to theImage Button
state, and thesrc
attribute is present, and its value has changed since the last time thetype
attribute was in theImage Button
state - the
input
element’stype
attribute is in theImage Button
state, and thesrc
attribute is set or changed
then unless the user agent cannot support images, or its support for images has been disabled,
or the user agent only fetches images on demand, or the src
attribute’s value is the empty string, the user agent must parse the value of the src
attribute value, relative to the element’s node document, and if that is successful, run these substeps:
- Let request be a new request whose URL is the resulting URL string, client is the element’s node document’s
Window
object’s environment settings object, type is "image
", destination is "subresource
", omit-Origin
-header flag is set, credentials mode is "include
", and whose use-URL-credentials flag is set. - Fetch request.
Fetching the image must delay the load event of the element’s node document until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.
If the image was successfully obtained, with no network errors, and the image’s type is a supported image type, and the image is a valid image of that type, then the image is said to be available. If this is true before the image is completely downloaded, each task that is queued by the networking task source while the image is being fetched must update the presentation of the image appropriately.
The user agent should apply the image sniffing rules to determine the type of the image, with the image’s associated Content-Type headers giving the official type. If these rules are not applied, then the type of the image must be the type given by the image’s associated Content-Type headers.
User agents must not support non-image resources with the input
element. User
agents must not run executable code embedded in the image resource. User agents must only display
the first page of a multipage resource. User agents must not allow the resource to act in an
interactive fashion, but should honor any animation in the resource.
The task that is queued by the networking task source once the resource has been fetched, must, if the
download was successful and the image is available, queue a task to fire a simple event named load
at the input
element; and otherwise, if the fetching
process fails without a response from the remote server, or completes but the image is not a valid
or supported image, queue a task to fire a simple event named error
on the input
element.
The alt
attribute provides the textual label for
the button for users and user agents who cannot use the image. The alt
attribute must be present, and must contain a non-empty string
giving the label that would be appropriate for an equivalent button if the image was
unavailable.
The input
element supports dimension attributes.
If the src
attribute is set, and the image is available and the user agent is configured to display that image,
then: The element represents a control for selecting a coordinate from the image specified by the src
attribute; if the element is mutable, the user agent should allow the user to select this coordinate, and the element’s activation
behavior is as follows: if the element has a form owner, and the element’s node document is fully active, take the user’s selected coordinate, and submit the input
element’s form owner from the input
element. If the user activates the control without explicitly
selecting a coordinate, then the coordinate (0,0) must be assumed.
Otherwise, the element represents a submit button whose label is given by the
value of the alt
attribute; if the element is mutable, then the element’s activation behavior is as
follows: if the element has a form owner, and the element’s node document is fully active, set the selected
coordinate to (0,0), and submit the input
element’s form owner from the input
element.
In either case, if the element is mutable but has no form owner or the element’s node document is not fully active, then its activation behavior must be to do nothing. If the element is not mutable, it has no activation behavior.
The selected coordinate must consist of an x-component and a y-component. The coordinates represent the position relative to the edge of the image, with the coordinate space having the positive x direction to the right, and the positive y direction downwards.
The x-component must be a valid integer representing a number x in the range -(borderleft+paddingleft) ≤ x ≤ width+borderright+paddingright, where width is the rendered width of the image, borderleft is the width of the border on the left of the image, paddingleft is the width of the padding on the left of the image, borderright is the width of the border on the right of the image, and paddingright is the width of the padding on the right of the image, with all dimensions given in CSS pixels.
The y-component must be a valid integer representing a number y in the range -(bordertop+paddingtop) ≤ y ≤ height+borderbottom+paddingbottom, where height is the rendered height of the image, bordertop is the width of the border above the image, paddingtop is the width of the padding above the image, borderbottom is the width of the border below the image, and paddingbottom is the width of the padding below the image, with all dimensions given in CSS pixels.
Where a border or padding is missing, its width is zero CSS pixels.
The formaction
, formenctype
, formmethod
, formnovalidate
, and formtarget
attributes are attributes for form
submission.
- image .
width
[ = value ] - image .
height
[ = value ] -
These attributes return the actual rendered dimensions of the image, or zero if the dimensions are not known.
They can be set, to change the corresponding content attributes.
The following common input
element content attributes and IDL attributes apply to the element: alt
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, src
, and width
content attributes; value
IDL attribute.
The value
IDL attribute is in mode default.
The following content attributes must not be specified and do not apply to the
element: accept
, autocomplete
, checked
, dirname
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, and step
.
The element’s value
attribute must be omitted.
The following IDL attributes and methods do not apply to the element: checked
, files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
The input
and change
events do not apply.
Many aspects of this state’s behavior are similar to the behavior of the img
element. Readers are encouraged to read that section, where many of the same
requirements are described in more detail.
<form action="process.cgi"> <input type=image src=map.png name=where alt="Show location list"> </form>
If the user clicked on the image at coordinate (127,40) then the URL used to submit the form
would be "process.cgi?where.x=127&where.y=40
".
(In this example, it’s assumed that for users who don’t see the map, and who instead just see a button labeled "Show location list", clicking the button will cause the server to show a list of locations to pick from instead of the map.)
4.10.5.1.21. Reset Button state (type=reset
)
- Allowed ARIA role attribute values:
button
(default - do not set).- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Reset Button
state, the rules in this section
apply.
The input
element represents a button that, when activated, resets
the form. If the element has a value
attribute, the button’s label must be the value of that attribute; otherwise, it must be an
implementation-defined string that means "Reset" or some such. The element is a button.
Since the default label is implementation-defined, and the width of the button typically depends on the button’s label, the button’s width can leak a few bits of fingerprintable information. These bits are likely to be strongly correlated to the identity of the user agent and the user’s locale.
If the element is mutable, then the element’s activation behavior, if the element has a form owner and the element’s node document is fully active, is to reset the form owner; otherwise, it is to do nothing.
If the element is not mutable, it has no activation behavior.
Constraint validation: The element is barred from constraint validation.
The value
IDL attribute applies to this element and is in mode default.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, autocomplete
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
The input
and change
events do not apply.
4.10.5.1.22. Button state (type=button
)
- Allowed ARIA role attribute values:
button
(default - do not set),link
,menuitem
,menuitemcheckbox
,menuitemradio
,radio
orswitch
.- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles.
When an input
element’s type
attribute is in
the Button state, the rules in this section apply.
The input
element represents a button with no default behavior. A
label for the button must be provided in the value
attribute, though it may be the empty string. If the element has a value
attribute,
the button’s label must be the value of that attribute; otherwise, it must be the empty string.
The element is a button.
If the element is mutable, the element’s activation behavior is to do nothing.
If the element is not mutable, it has no activation behavior.
Constraint validation: The element is barred from constraint validation.
The value
IDL attribute applies to this element and is in mode default.
The following content attributes must not be specified and do not apply to the
element: accept
, alt
, autocomplete
, checked
, dirname
, formaction
, formenctype
, formmethod
, formnovalidate
, formtarget
, height
, inputmode
, list
, max
, maxlength
, min
, minlength
, multiple
, pattern
, placeholder
, readonly
, required
, size
, src
, step
, and width
.
The following IDL attributes and methods do not apply to the element: checked
, files
, list
, selectionStart
, selectionEnd
, selectionDirection
, valueAsDate
, and valueAsNumber
IDL attributes; select()
, setRangeText()
, setSelectionRange()
, stepDown()
, and stepUp()
methods.
The input
and change
events do not apply.
4.10.5.2. Implementation notes regarding localization of form controls
This section is non-normative.
The formats shown to the user in date, time, and number controls is independent of the format used for form submission.
Browsers should use user interfaces that present locale-affected formats such as dates, times,
and numbers according to the conventions of either the locale implied by the input
element’s language or the user’s preferred locale. Using the page’s locale will ensure
consistency with page-provided data.
For example, it would be confusing to users if an American English page claimed that a Cirque De Soleil show was going to be showing on 02/03, but their browser, configured to use the British English locale, only showed the date 03/02 in the ticket purchase date picker. Using the page’s locale would at least ensure that the date was presented in the same format everywhere. (There’s still a risk that the user would end up arriving a month late, of course, but there’s only so much that can be done about such cultural differences...)
4.10.5.3. Common input
element attributes
These attributes only apply to an input
element if its type
attribute is in a state whose definition
declares that the attribute applies. When an attribute doesn’t apply to an input
element, user agents must ignore the attribute, regardless of the requirements and definitions below.
4.10.5.3.1. The maxlength
and minlength
attributes
The maxlength
attribute, when it applies,
is a form control maxlength
attribute controlled by the input
element’s dirty value flag.
The minlength
attribute, when it applies,
is a form control minlength
attribute controlled by the input
element’s dirty value flag.
If the input
element has a maximum allowed value length, then the code-unit length of the value of the element’s value
attribute must be
equal to or less than the element’s maximum allowed value length.
<label>What are you doing? <input name=status maxlength=140></label>
<p><label>Username: <input name=u required></label> <p><label>Password: <input name=p required minlength=12></label>
4.10.5.3.2. The size
attribute
The size
attribute gives the number of
characters that, in a visual rendering, the user agent is to allow the user to see while editing
the element’s value.
The size
attribute, if specified, must have a value that
is a valid non-negative integer greater than zero.
If the attribute is present, then its value must be parsed using the rules for parsing non-negative integers, and if the result is a number greater than zero, then the user agent should ensure that at least that many characters are visible.
The size
IDL attribute is limited to only
non-negative numbers greater than zero and has a default value of 20.
4.10.5.3.3. The readonly
attribute
The readonly
attribute is a boolean
attribute that controls whether or not the user can edit the form control.
When specified, the element is not mutable.
Constraint validation: If the readonly
attribute is specified
on an input
element, the element is barred from constraint validation.
The difference between disabled
and readonly
is that
read-only controls are still focusable, so the user can still select the text and interact with it,
whereas disabled controls are entirely non-interactive.
Only text controls can be made read-only.
<form action="products.cgi" method="post" enctype="multipart/form-data"> <table> <tr> <th> Product ID <th> Product name <th> Price <th> Action <tr> <td> <input readonly="readonly" name="1.pid" value="H412"> <td> <input required="required" name="1.pname" value="Floor lamp Ulke"> <td> $<input required="required" type="number" min="0" step="0.01" name="1.pprice" value="49.99"> <td> <button formnovalidate="formnovalidate" name="action" value="delete:1">Delete</button> <tr> <td> <input readonly="readonly" name="2.pid" value="FG28"> <td> <input required="required" name="2.pname" value="Table lamp Ulke"> <td> $<input required="required" type="number" min="0" step="0.01" name="2.pprice" value="24.99"> <td> <button formnovalidate="formnovalidate" name="action" value="delete:2">Delete</button> <tr> <td> <input required="required" name="3.pid" value="" pattern="[A-Z0-9]+"> <td> <input required="required" name="3.pname" value=""> <td> $<input required="required" type="number" min="0" step="0.01" name="3.pprice" value=""> <td> <button formnovalidate="formnovalidate" name="action" value="delete:3">Delete</button> </table> <p> <button formnovalidate="formnovalidate" name="action" value="add">Add</button> </p> <p> <button name="action" value="update">Save</button> </p> </form>
4.10.5.3.4. The required
attribute
The required
attribute is a boolean attribute. When specified, the element is required.
Constraint validation: If the element is required, and its value
IDL attribute applies and is in the mode value,
and the element is mutable, and the element’s value is the empty string,
then the element is suffering from being missing.
<h1>Create new account</h1> <form action="/newaccount" method=post oninput='up2.setCustomValidity(up2.value != up.value ? "Passwords do not match." : "")'> <p> <label for="username">E-mail address:</label> <input id="username" type=email required name=un> <p> <label for="password1">Password:</label> <input id="password1" type=password required name=up> <p> <label for="password2">Confirm password:</label> <input id="password2" type=password name=up2> <p> <input type=submit value="Create account"> </form>
required
attribute is
satisfied if any of the radio buttons in the group is
selected. Thus, in the following example, any of the radio buttons can be checked, not just the
one marked as required:
<fieldset> <legend>Did the movie pass the Bechdel test?</legend> <p><label><input type="radio" name="bechdel" value="no-characters"> No, there are not even two female characters in the movie. </label> <p><label><input type="radio" name="bechdel" value="no-names"> No, the female characters never talk to each other. </label> <p><label><input type="radio" name="bechdel" value="no-topic"> No, when female characters talk to each other it’s always about a male character. </label> <p><label><input type="radio" name="bechdel" value="yes" required> Yes. </label> <p><label><input type="radio" name="bechdel" value="unknown"> I don’t know. </label> </fieldset>
To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.
4.10.5.3.5. The multiple
attribute
The multiple
attribute is a boolean attribute that indicates whether the user is to be allowed to specify more than one
value.
<label>Cc: <input type=email multiple name=cc></label>
If the user had, amongst many friends in their user contacts database, two friends "Arthur Dent" (with address "art@example.net") and "Adam Josh" (with address "adamjosh@example.net"), then, after the user has typed "a", the user agent might suggest these two e-mail addresses to the user.
The page could also link in the user’s contacts database from the site:
<label>Cc: <input type=email multiple name=cc list=contacts></label> ... <datalist id="contacts"> <option value="hedral@damowmow.com"> <option value="pillar@example.com"> <option value="astrophy@cute.example"> <option value="astronomy@science.example.org"> </datalist>
Suppose the user had entered "bob@example.net" into this text field, and then started typing a
second e-mail address starting with "a". The user agent might show both the two friends mentioned
earlier, as well as the "astrophy" and "astronomy" values given in the datalist
element.
<label>Attachments: <input type=file multiple name=att></label>
4.10.5.3.6. The pattern
attribute
The pattern
attribute specifies a regular
expression against which the control’s value, or, when the multiple
attribute applies and is set, the control’s values, are to be checked.
If specified, the attribute’s value must match the JavaScript Pattern production. [ECMA-262]
If an input
element has a pattern
attribute specified, and the attribute’s value, when compiled as a JavaScript regular expression
with only the "u
" flag specified, compiles successfully, then the resulting regular expression is the element’s compiled pattern regular expression. If the element has no such attribute, or if the
value doesn’t compile successfully, then the element has no compiled pattern regular
expression. [ECMA-262]
If the value doesn’t compile successfully, user agents are encouraged to log this fact in a developer console, to aid debugging.
Constraint validation: If the element’s value is not the empty string, and either the element’s multiple
attribute is not specified or it does not apply to the input
element given its type
attribute’s current state, and the element has a compiled pattern regular expression but that regular expression does not match the
entirety of the element’s value, then the element is suffering from a pattern mismatch.
Constraint validation: If the element’s value is not the empty string, and the element’s multiple
attribute is specified and applies to the input
element, and the element has
a compiled pattern regular expression but that regular expression does not match the
entirety of each of the element’s values, then the
element is suffering from a pattern mismatch.
The compiled pattern regular expression, when matched against a string, must have its start anchored to the start of the string and its end anchored to the end of the string.
This implies that the regular expression language used for this attribute is the
same as that used in JavaScript, except that the pattern
attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?:
at the start of the pattern and a )$
at the
end).
When an input
element has a pattern
attribute specified, authors should provide a description of the pattern in text near the
control. Authors may also include a title
attribute to give a description of the pattern. User agents may use
the contents of this attribute, if it is present, when informing the
user that the pattern is not matched, or at any other suitable time,
such as in a tooltip or read out by assistive technology when the
control gains focus.
Relying on the title
attribute for the visual display
of text content is currently discouraged as many user agents do not expose the attribute in an accessible manner
as required by this specification (e.g., requiring a pointing device such as a mouse to cause a tooltip to appear,
which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or
tablet).
<label> Part number: <input pattern="[0-9][A-Z]{3}" name="part" title="A part number is a digit followed by three uppercase letters."/> </label>
...could cause the user agent to display an alert such as:
A part number is a digit followed by three uppercase letters.You cannot submit this form when the field is incorrect.
When a control has a pattern
attribute, the title
attribute, if used, must describe the pattern. Additional
information could also be included, so long as it assists the user in filling in the control.
Otherwise, assistive technology would be impaired.
For instance, if the title attribute contained the caption of the control, assistive technology could end up saying something like The text you have entered does not match the required pattern. Birthday, which is not useful.
user agents may still show the title
in non-error situations (for
example, as a tooltip when hovering over the control), so authors should be careful not to word title
s as if an error has necessarily occurred.
4.10.5.3.7. The min
and max
attributes
Some form controls can have explicit constraints applied limiting the allowed range of values that the user can provide. Normally, such a range would be linear and continuous. A form control can have a periodic domain, however, in which case the form control’s broadest possible range is finite, and authors can specify explicit ranges within it that span the boundaries.
Specifically, the broadest range of a type=time
control is midnight to midnight (24 hours), and
authors can set both continuous linear ranges (such as 9pm to 11pm) and discontinuous ranges
spanning midnight (such as 11pm to 1am).
The min
and max
attributes indicate the allowed range of values for
the element.
Their syntax is defined by the section that defines the type
attribute’s current state.
If the element has a min
attribute, and the result of
applying the algorithm to convert a string to a
number to the value of the min
attribute is a number,
then that number is the element’s minimum; otherwise, if the type
attribute’s current state defines a default minimum, then that is the minimum; otherwise, the element has no minimum.
The min
attribute also defines the step base.
If the element has a max
attribute, and the result of
applying the algorithm to convert a string to a
number to the value of the max
attribute is a number,
then that number is the element’s maximum; otherwise, if the type
attribute’s current state defines a default maximum, then that is the maximum; otherwise, the element has no maximum.
If the element does not have a periodic domain, the max
attribute’s value
(the maximum) must not be less than the min
attribute’s value
(its minimum).
If an element that does not have a periodic domain has a maximum that is less than its minimum, then so long as the element has a value, it will either be suffering from an underflow or suffering from an overflow.
An element has a reversed range if it has a periodic domain and its maximum is less than its minimum.
An element has range limitations if it has a defined minimum or a defined maximum.
How these range limitations apply depends on whether the element has a multiple
attribute.
- If the element does not have a
multiple
attribute specified or if themultiple
attribute does not apply -
Constraint validation: When the element has a minimum and does not have a reversed range, and the result of applying the algorithm to convert a string to a number to the string given by the element’s value is a number, and the number obtained from that algorithm is less than the minimum, the element is suffering from an underflow.
Constraint validation: When the element has a maximum and does not have a reversed range, and the result of applying the algorithm to convert a string to a number to the string given by the element’s value is a number, and the number obtained from that algorithm is more than the maximum, the element is suffering from an overflow.
Constraint validation: When an element has a reversed range, and the result of applying the algorithm to convert a string to a number to the string given by the element’s value is a number, and the number obtained from that algorithm is more than the maximum and less than the minimum, the element is simultaneously suffering from an underflow and suffering from an overflow.
- If the element does have a
multiple
attribute specified and themultiple
attribute does apply -
Constraint validation: When the element has a minimum, and the result of applying the algorithm to convert a string to a number to any of the strings in the element’s values is a number that is less than the minimum, the element is suffering from an underflow.
Constraint validation: When the element has a maximum, and the result of applying the algorithm to convert a string to a number to any of the strings in the element’s values is a number that is more than the maximum, the element is suffering from an overflow.
<input name=bday type=date max="1979-12-31">
<input name=quantity required="" type="number" min="1" value="1">
<input name="sleepStart" type=time min="21:00" max="06:00" step="60" value="00:00">
4.10.5.3.8. The step
attribute
The step
attribute indicates the granularity
that is expected (and required) of the value or values,
by limiting the allowed values. The section that defines the type
attribute’s current state
also defines the default step, the step scale factor,
and in some cases the default step base,
which are used in processing the attribute as described below.
The step
attribute, if specified, must either have a
value that is a valid floating-point number that parses to a number that is greater than zero, or must have a
value that is an ASCII case-insensitive match for the string "any
".
The attribute provides the allowed value step for the element, as follows:
-
If the
step
attribute is absent, then the allowed value step is the default step multiplied by the step scale factor. -
Otherwise, if the attribute’s value is an ASCII case-insensitive match for the string "
any
", then there is no allowed value step. -
Otherwise, let step value be the result of running the rules for parsing floating-point number values, when they are applied to the
step
attribute’s value. -
If the previous step returned an error, or step value is zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.
-
If the element’s
type
attribute is in theDate and Time
,Date
,Month
,Week
, orTime
state, then round step value to the nearest whole number using the "round to nearest + round half up" technique, unless the value is less-than one, in which case let step value be 1. -
The allowed value step is step value multiplied by the step scale factor.
The step base is the value returned by the following algorithm:
-
If the element has a
min
content attribute, and the result of applying the algorithm to convert a string to a number to the value of themin
content attribute is not an error, then return that result and abort these steps. -
If the element has a
value
content attribute, and the result of applying the algorithm to convert a string to a number to the value of thevalue
content attribute is not an error, then return that result and abort these steps. -
If a default step base is defined for this element given its
type
attribute’s state, then return it and abort these steps. -
Return zero.
How these range limitations apply depends on whether the element has a multiple
attribute.
- If the element does not have a
multiple
attribute specified or if themultiple
attribute does not apply -
Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the value is a number, and that number is not step aligned, the element is suffering from a step mismatch.
- If the element does have a
multiple
attribute specified and themultiple
attribute does apply -
Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to any of the strings in the values is a number that is not step aligned, the element is suffering from a step mismatch.
<input name=opacity type=range min=0 max=1 step=0.00392156863>
<input name=favtime type=time step=any>
Normally, time controls are limited to an accuracy of one minute.
4.10.5.3.9. The list
attribute
The list
attribute is used to identify an
element that lists predefined options suggested to the user.
If present, its value must be the ID of a datalist
element in the same document.
The suggestions source element is the first element in
the document in tree order to have an ID equal to the
value of the list
attribute, if that element is a datalist
element. If there is no list
attribute,
or if there is no element with that ID, or if the first element
with that ID is not a datalist
element, then there is
no suggestions source element.
If there is a suggestions source element, then, when
the user agent is allowing the user to edit the input
element’s value, the user agent should offer the suggestions represented by
the suggestions source element to the user in a manner
suitable for the type of control used. The user agent may use the suggestion’s label to identify the suggestion if appropriate.
User agents are encouraged to filter the suggestions represented by the suggestions source element when the number of suggestions is
large, including only the most relevant ones (e.g., based on the user’s input so far). No precise
threshold is defined, but capping the list at four to seven values is reasonable.
User agents that perform filtering should implement substring matching on the label
attribute.
Existing user agents filter on either value
or label
so the behavior may be inconsistent.
How user selections of suggestions are handled depends on whether the element is a control accepting a single value only, or whether it accepts multiple values:
- If the element does not have a
multiple
attribute specified or if themultiple
attribute does not apply -
When the user selects a suggestion, the
input
element’s value must be set to the selected suggestion’s value, as if the user had written that value themself. - If the element’s
type
attribute is in theRange
state and the element has amultiple
attribute specified -
When the user selects a suggestion, the user agent must identify which value in the element’s values the user intended to update, and must then update the element’s values so that the relevant value is changed to the value given by the selected suggestion’s value, as if the user had themself set it to that value.
- If the element’s
type
attribute is in theE-mail
state and the element has amultiple
attribute specified -
When the user selects a suggestion, the user agent must either add a new entry to the
input
element’s values, whose value is the selected suggestion’s value, or change an existing entry in theinput
element’s values to have the value given by the selected suggestion’s value, as if the user had themself added an entry with that value, or edited an existing entry to be that value. Which behavior is to be applied depends on the user interface in a user-agent-defined manner.
If the list
attribute does not apply, there is no suggestions source element.
<label>Homepage: <input name=hp type=url list=hpurls></label> <datalist id=hpurls> <option value="https://www.google.com/" label="Google"> <option value="https://www.reddit.com/" label="Reddit"> </datalist>
Other URLs from the user’s history might show also; this is up to the user agent.
If the autocompletion list is merely an aid, and is not important to the content, then simply
using a datalist
element with children option
elements is enough. To
prevent the values from being rendered in legacy user agents, they need to be placed inside the value
attribute instead of inline.
<p> <label> Enter a breed: <input type="text" name="breed" list="breeds"> <datalist id="breeds"> <option value="Abyssinian"> <option value="Alpaca"> <!-- ... --> </datalist> </label> </p>
However, if the values need to be shown in legacy user agents, then fallback content can be placed
inside the datalist
element, as follows:
<p> <label> Enter a breed: <input type="text" name="breed" list="breeds"> </label> <datalist id="breeds"> <label> or select one from the list: <select name="breed"> <option value=""> (none selected) <option>Abyssinian <option>Alpaca <!-- ... --> </select> </label> </datalist> </p>
The fallback content will only be shown in user agents that don’t support datalist
. The
options, on the other hand, will be detected by all user agents, even though they are not children of the datalist
element.
Note that if an option
element used in a datalist
is selected
, it will be selected by default by legacy user agents
(because it affects the select
), but it will not have any effect on the input
element in user agents that support datalist
.
4.10.5.3.10. The placeholder
attribute
The placeholder
attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the
control has no value. A hint could be a sample value or a brief description of the expected
format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or
U+000D CARRIAGE RETURN (CR) characters.
The placeholder
attribute should not be used as a
replacement for a label
. For a longer hint or other advisory text, place the text
next to the control.
Use of the placeholder
attribute as a replacement for a label
can reduce the
accessibility and usability of the control for a range of users including older
users and users with cognitive, mobility, fine motor skill or vision impairments.
While the hint given by the control’s label
is shown at all times, the short
hint given in the placeholder
attribute is only shown before the user enters a value. Furthermore, placeholder
text may be mistaken for
a pre-filled value, and as commonly implemented the default color of the placeholder text
provides insufficient contrast and the lack of a separate visible label
reduces the size of the hit region available for setting focus on the control.
User agents should present this hint to the user, after having stripped line breaks from it, when the element’s value is the empty string, especially if the control is not focused.
If a user agent normally doesn’t show this hint to the user when the control is focused, then the user agent should nonetheless show the hint for the control if it
was focused as a result of the autofocus
attribute, since
in that case the user will not have had an opportunity to examine the control before focusing
it.
placeholder
attribute:
<fieldset> <legend>Mail Account</legend> <p><label>Name: <input type="text" name="fullname" placeholder="John Ratzenberger"></label></p> <p><label>Address: <input type="email" name="address" placeholder="john@example.net"></label></p> <p><label>Password: <input type="password" name="password"></label></p> <p><label>Description: <input type="text" name="desc" placeholder="My Email Account"></label></p> </fieldset>
<input name=t1 type=tel placeholder="‫ رقم الهاتف 1 ‮"> <input name=t2 type=tel placeholder="‫ رقم الهاتف 2 ‮">
For slightly more clarity, here’s the same example using numeric character references instead of inline Arabic:
<input name=t1 type=tel placeholder="‫رقم الهاتف 1‮"> <input name=t2 type=tel placeholder="‫رقم الهاتف 2‮">
4.10.5.4. Common input
element APIs
- input .
value
[ = value ] -
Returns the current value of the form control.
Can be set, to change the value.
Throws an "
InvalidStateError
"DOMException
if it is set to any value other than the empty string when the control is aFile Upload
control. - input .
checked
[ = value ] -
Returns the current checkedness of the form control.
Can be set, to change the checkedness.
- input .
files
-
Returns a
FileList
object listing the selected files of the form control.Returns null if the control isn’t a file control.
- input .
valueAsDate
[ = value ] -
Returns a
Date
object representing the form control’s value, if applicable; otherwise, returns null.Can be set, to change the value.
Throws an "
InvalidStateError
"DOMException
if the control isn’t date- or time-based. - input .
valueAsNumber
[ = value ] -
Returns a number representing the form control’s value, if applicable;
otherwise, returns NaN.
Can be set, to change the value. Setting this to NaN will set the underlying value to the empty string.
Throws an "
InvalidStateError
"DOMException
if the control is neither date- or time-based nor numeric. - input .
stepUp
( [ n ] ) - input .
stepDown
( [ n ] ) -
Changes the form control’s value by the value given in the
step
attribute, multiplied by n. The default value for n is 1.Throws "
InvalidStateError
"DOMException
if the control is neither date- or time-based nor numeric, or if thestep
attribute’s value is "any
". - input .
list
- Returns the
datalist
element indicated by thelist
attribute.
The value
IDL attribute allows scripts to
manipulate the value of an input
element. The
attribute is in one of the following modes, which define its behavior:
- value
-
On getting, it must return the current value of the element. On setting, it must set the element’s value to the new value, set the element’s dirty value flag to true, invoke the value sanitization algorithm, if the element’s
type
attribute’s current state defines one, and then, if the element has a text entry cursor position, should move the text entry cursor position to the end of the text field, unselecting any selected text and resetting the selection direction to none. - default
-
On getting, if the element has a
value
attribute, it must return that attribute’s value; otherwise, it must return the empty string. On setting, it must set the element’svalue
attribute to the new value. - default/on
-
On getting, if the element has a
value
attribute, it must return that attribute’s value; otherwise, it must return the string "on
". On setting, it must set the element’svalue
attribute to the new value. - filename
-
On getting, it must return the string "
C:\fakepath\
" followed by the name of the first file in the list of selected files, if any, or the empty string if the list is empty. On setting, if the new value is the empty string, it must empty the list of selected files; otherwise, it must throw an "InvalidStateError
"DOMException
.This "fakepath" requirement is a sad accident of history. See the example in the
File Upload
state section for more information.Since path components are not permitted in file names in the list of selected files, the "
\fakepath\
" cannot be mistaken for a path component.
The checked
IDL attribute allows scripts to
manipulate the checkedness of an input
element. On getting, it must return the current checkedness of the element; and on setting, it must set the
element’s checkedness to the new value and set the
element’s dirty checkedness flag to
true.
The files
IDL attribute allows scripts to
access the element’s selected files. On
getting, if the IDL attribute applies, it must return a FileList
object that represents the current selected files. The same object must be returned
until the list of selected files changes. If
the IDL attribute does not apply, then it must instead return
null. [FILEAPI]
The valueAsDate
IDL attribute represents
the value of the element, interpreted as a date.
On getting, if the valueAsDate
attribute does not apply, as defined for the input
element’s type
attribute’s current state, then return null. Otherwise, run
the algorithm to convert a string to a Date
object defined for that state to the element’s value; if the algorithm returned a Date
object, then
return it, otherwise, return null.
On setting, if the valueAsDate
attribute does not apply, as defined for the input
element’s type
attribute’s current state, then throw an InvalidStateError
exception; otherwise, if the new value is not null and not a Date
object throw a TypeError
exception; otherwise if the new value is null or a Date
object representing the NaN time value, then set the value of the element to the empty string; otherwise, run the algorithm to convert a Date
object to
a string, as defined for that state, on the new value, and set the value of the element to the resulting string.
The valueAsNumber
IDL attribute
represents the value of the element, interpreted as a
number.
On getting, if the valueAsNumber
attribute does not apply, as defined for the input
element’s type
attribute’s current state, then return a Not-a-Number (NaN)
value. Otherwise, if the valueAsDate
attribute applies, run the algorithm to convert a string to a Date
object defined for that state to the element’s value; if the algorithm returned a Date
object, then
return the time value of the object (the number of milliseconds from midnight UTC the
morning of 1970-01-01 to the time represented by the Date
object), otherwise, return
a Not-a-Number (NaN) value. Otherwise, run the algorithm to convert a string to a number defined for that state to the element’s value; if the
algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
On setting, if the new value is infinite, then throw a TypeError
exception.
Otherwise, if the valueAsNumber
attribute does not apply, as defined for the input
element’s type
attribute’s current state, then throw an InvalidStateError
exception. Otherwise, if the new value is a Not-a-Number (NaN)
value, then set the value of the element to the empty
string. Otherwise, if the valueAsDate
attribute applies, run the algorithm to convert a Date
object to a
string defined for that state, passing it a Date
object whose time
value is the new value, and set the value of the
element to the resulting string. Otherwise, run the algorithm to convert a number to a string, as
defined for that state, on the new value, and set the value of the element to the resulting string.
The stepDown(n)
and stepUp(n)
methods, when invoked, must run the following algorithm:
-
If the
stepDown()
andstepUp()
methods do not apply, as defined for theinput
element’stype
attribute’s current state, then throw an "InvalidStateError
"DOMException
, and abort these steps. -
If the element has no allowed value step, then throw an "
InvalidStateError
"DOMException
, and abort these steps. -
If the element has a minimum and a maximum and the minimum is greater than the maximum, then abort these steps.
-
If the element has a minimum and a maximum and there is no step aligned value greater than or equal to the element’s minimum and less than or equal to the element’s maximum, then abort these steps.
-
If applying the algorithm to convert a string to a number to the string given by the element’s value does not result in an error, then let value be the result of that algorithm. Otherwise, let value be zero.
-
Let valueBeforeStepping be value.
-
If value is not step aligned, then:
-
If the method invoked was the
stepDown()
method, then step-align value with negative preference. Otherwise step-align value with positive preference. In either case, let value be the result.This ensures that the value first snaps to a step-aligned value when it doesn’t start step-aligned. For example, starting with the followinginput
withvalue
of 3:<input type="number" value="3" min="1" max="10" step="2.6">
Invoking the
stepUp()
method will snap thevalue
to 3.6; subsequent invocations will increment the value by 2.6 (e.g., 6.2, then 8.8). Likewise, the followinginput
element in theWeek
state will also step-align in similar fashion, though in this state, thestep
value is rounded to 3, per the derivation of the allowed value step.<input type="week" value="2016-W20" min="2016-W01" max="2017-W01" step="2.6">
Invoking
stepUp()
will result in avalue
of "2016-W22
" because the nearest step-aligned value from the step base of "2016-W01
" (themin
value) with 3 weekstep
s that is greater than thevalue
of "2016-W20
" is "2016-W22
" (i.e.: W01, W04, W07, W10, W13, W16, W19, W22).
Otherwise (value is step aligned), run the following substeps:
-
Let n be the argument.
-
Let delta be the allowed value step multiplied by n.
-
If the method invoked was the
stepDown()
method, negate delta. -
Let value be the result of adding delta to value.
-
-
If the element has a minimum, and value is less than that minimum, then set value to the step-aligned minimum value with positive preference.
-
If the element has a maximum, and value is greater than that maximum, then set value to the step-aligned maximum value with negative preference.
-
If either the method invoked was the
stepDown()
method and value is greater than valueBeforeStepping, or the method invoked was thestepUp()
method and value is less than valueBeforeStepping, then abort these steps. -
Let value as string be the result of running the algorithm to convert a number to a string, as defined for the
input
element’stype
attribute’s current state, on value. -
Set the value of the element to value as string.
To determine if a value v is step aligned do the following:
This algorithm checks to see if a value falls along an input
element’s
defined step
intervals, with the interval’s origin at the step base value. It is
used to determine if the element’s value is suffering from a step mismatch and for various checks in the stepUp()
and stepDown()
methods.
-
Subtract the step base from v and let the result be relative distance.
-
If dividing the relative distance by the allowed value step results in a value with a remainder then v is not step aligned. Otherwise it is step aligned.
To step-align a value v with either negative preference or positive preference, do the following:
negative preference selects a step-aligned value that is less than or equal to v, while positive preference step-aligns with a value greater than or equal to v.
-
Subtract the step base from v and let the result be relative distance.
-
Let step interval count be the result of integer dividing (or divide and throw out any remainder) relative distance by the allowed value step.
-
Let candidate be the step interval count multiplied by the allowed value step.
-
If this algorithm was invoked with negative preference and the value of v is less than candidate, then decrement candidate by the allowed value step.
Otherwise, if this algorithm was invoked with positive preference and the value of v is greater than candidate, then increment candidate by the allowed value step.
-
The step-aligned value is candidate. Return candidate.
The list
IDL attribute must return the
current suggestions source element, if any, or null otherwise.
4.10.5.5. Common event behaviors
When the input
and change
events apply (which is the case for all input
controls other than buttons and those with the type
attribute in the state), the events are fired to indicate that the
user has interacted with the control. The
input
event fires whenever the user has modified the data of the control. The change
event fires when the value is committed, if
that makes sense for the control, or else when the control loses focus. In all cases, the input
event comes before the corresponding change
event (if any).
When an input
element has a defined activation behavior, the rules
for dispatching these events, if they apply, are given
in the section above that defines the type
attribute’s
state. (This is the case for all input
controls with the type
attribute in the Checkbox
state, the Radio Button
state, or the File Upload
state.)
For input
elements without a defined activation behavior, but to
which these events apply, and for which the user
interface involves both interactive manipulation and an explicit commit action, then when the user
changes the element’s value, the user agent must queue a task to fire a simple event that bubbles named input
at the input
element, and any time the user
commits the change, the user agent must queue a task to fire a simple
event that bubbles named change
at the input
element.
An example of a user interface involving both interactive manipulation and a
commit action would be a Range
controls that use a
slider, when manipulated using a pointing device. While the user is dragging the control’s knob, input
events would fire whenever the position changed,
whereas the change
event would only fire when the user
let go of the knob, committing to a specific value.
For input
elements without a defined activation behavior, but to
which these events apply, and for which the user
interface involves an explicit commit action but no intermediate manipulation, then any time the
user commits a change to the element’s value, the user
agent must queue a task to first fire a simple event that bubbles named input
at the input
element, and then fire a simple event that bubbles named change
at the input
element.
An example of a user interface with a commit action would be a Color
control that consists of a single button that brings
up a color wheel: if the value only changes when the dialog
is closed, then that would be the explicit commit action. On the other hand, if manipulating the
control changes the color interactively, then there might be no commit action.
Another example of a user interface with a commit action would be a Date
control that allows both text-based user input and user
selection from a drop-down calendar: while text input does not have an explicit commit step,
selecting a date from the drop down calendar and then dismissing the drop down would be a commit
action.
The Range
control is also an example of a
user interface that has a commit action when used with a pointing device (rather than a keyboard):
during the time that the pointing device starts manipulating the slider until the time that the
slider is released, no commit action is taken (though input
events are fired as the
value is changed). Only after the slider is release is the commit action taken.
For input
elements without a defined activation behavior, but to
which these events apply, any time the user causes the
element’s value to change without an explicit commit
action, the user agent must queue a task to fire a simple event that
bubbles named input
at the input
element. The
corresponding change
event, if any, will be fired when
the control loses focus.
Examples of a user changing the element’s value would include the user typing into a text field, pasting a new value into the field, or undoing an edit in that field. Some user interactions do not cause changes to the value, e.g., hitting the "delete" key in an empty text field, or replacing some text in the field with text from the clipboard that happens to be exactly the same text.
A Range
control in the form of a
slider that the user has focused and is interacting with using a keyboard would be
another example of the user changing the element’s value without a commit step.
In the case of tasks that just fire an input
event, user agents may wait for a suitable break in the
user’s interaction before queuing the tasks; for example, a
user agent could wait for the user to have not hit a key for 100ms, so as to only fire the event
when the user pauses, instead of continuously for each keystroke.
When the user agent is to change an input
element’s value on behalf of the user (e.g., as part of a form prefilling
feature), the user agent must queue a task to first update the value accordingly, then fire a simple event that
bubbles named input
at the input
element,
then fire a simple event that bubbles named change
at the input
element.
These events are not fired in response to changes made to the values of form controls by scripts. (This is to make it easier to update the values of form controls in response to the user manipulating the controls, without having to then filter out the script’s own changes to avoid an infinite loop.)
The task source for these tasks is the user interaction task source.
4.10.6. The button
element
- Categories:
- Flow content.
- Phrasing content.
- Interactive content.
- listed, labelable, submittable, and reassociateable form-associated element.
- Palpable content.
- Contexts in which this element can be used:
- Where phrasing content is expected.
- Content model:
- Phrasing content, but there must be no interactive content descendant.
- Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
autofocus
- Automatically focus the form control when the page is loadeddisabled
- Whether the form control is disabledform
- Associates the control with aform
elementformaction
- URL to use for §4.10.21 Form submissionformenctype
- Form data set encoding type to use for §4.10.21 Form submissionformmethod
- HTTP method to use for §4.10.21 Form submissionformnovalidate
- Bypass form control validation for §4.10.21 Form submissionformtarget
- browsing context for §4.10.21 Form submissionmenu
- Specifies the element’s designated pop-up menuname
- Name of form control to use for §4.10.21 Form submission and in theform.elements
APItype
- Type of buttonvalue
- Value to be used for §4.10.21 Form submission- Allowed ARIA role attribute values:
button
(default - do not set),link
,menuitem
,menuitemcheckbox
,menuitemradio
,radio
orswitch
.- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles. - DOM interface:
-
interface HTMLButtonElement : HTMLElement { attribute boolean autofocus; attribute boolean disabled; readonly attribute HTMLFormElement? form; attribute DOMString formAction; attribute DOMString formEnctype; attribute DOMString formMethod; attribute boolean formNoValidate; attribute DOMString formTarget; attribute DOMString name; attribute DOMString type; attribute DOMString value; attribute HTMLMenuElement? menu; readonly attribute boolean willValidate; readonly attribute ValidityState validity; readonly attribute DOMString validationMessage; boolean checkValidity(); boolean reportValidity(); void setCustomValidity(DOMString error); [SameObject] readonly attribute NodeList labels; };
The button
element represents a control allowing a user to trigger actions, when enabled.
It is labeled by its content.
The element is a button.
The type
attribute controls the behavior of
the button when it is activated. It is an enumerated attribute. The following table
lists the keywords and states for the attribute — the keywords in the left column map to the
states in the cell in the second column on the same row as the keyword.
Keyword | State | Brief description |
---|---|---|
submit
| submit button | Submits the form. |
reset
| reset button | Resets the form. |
button
| Button | Does nothing. |
menu
| Menu | Shows a menu. |
The missing value default is the submit button state.
If the type
attribute is in the submit button state, the element is specifically a submit button.
Constraint validation: If the type
attribute is in the reset button state, the Button state, or the Menu state, the element is barred from constrain validation.
When a button
element is not disabled,
its activation behavior element is to run the steps defined in the following list for
the current state of the element’s type
attribute:
- submit button
- If the element has a form owner and the element’s node document is fully active, the element must submit the form owner from the
button
element. - reset button
- If the element has a form owner and the element’s node document is fully active, the element must reset the form owner.
- Button
- Do nothing.
- Menu
-
The element must follow these steps:
- If the
button
is not being rendered, abort these steps. - If the
button
element’s node document is not fully active, abort these steps. - Let menu be the element’s designated pop-up menu, if any. If there isn’t one, then abort these steps.
- Fire a trusted event with the name
show
at menu, using theRelatedEvent
interface, with therelatedTarget
attribute initialized to thebutton
element. The event must be cancelable. - If the event is not canceled, then build and
show the menu for menu, with the
button
element as the subject.
- If the
The form
attribute is used to explicitly associate the button
element with its form owner. The name
attribute represents the element’s name. The disabled
attribute is used to make the control non-interactive and
to prevent its value from being submitted. The autofocus
attribute controls focus. The formaction
, formenctype
, formmethod
, formnovalidate
, and formtarget
attributes are attributes for form submission.
The formnovalidate
attribute can be
used to make submit buttons that do not trigger the constraint validation.
The formaction
, formenctype
, formmethod
, formnovalidate
, and formtarget
must not be specified if the element’s type
attribute is not in the submit button state.
The value
attribute gives the element’s value
for the purposes of form submission. The element’s value is
the value of the element’s value
attribute, if there is
one, or the empty string otherwise.
A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.
If the element’s type
attribute is in the Menu state, the menu
attribute must be specified to give the element’s
menu. The value must be the ID of a menu
element in
the same tree whose type
attribute is in
the context menu state. The attribute must not be specified if
the element’s type
attribute is not in the Menu state.
A button
element’s designated pop-up menu is the first element in the button
's tree whose ID is that given by the button
element’s menu
attribute, if there is such an element and
its type
attribute is in the context menu state; otherwise, the element has no designated pop-up
menu.
The value
and menu
IDL attributes must reflect the content attributes of the same name.
The type
IDL attribute must reflect the content attribute of the same name, limited to only known values.
The willValidate
, validity
, and validationMessage
IDL attributes, and
the checkValidity()
, reportValidity()
, and setCustomValidity()
methods, are part of
the constraint validation API.
The labels
IDL attribute provides a list of the element’s label
s.
The autofocus
, disabled
, form
, and name
IDL attributes are
part of the element’s forms API.
<button type=button onclick="alert('This 15-20 minute piece was composed by George Gershwin.')"> Show hint </button>
4.10.7. The select
element
- Categories:
- Flow content.
- Phrasing content.
- Interactive content.
- listed, labelable, submittable, resettable, and reassociateable form-associated element.
- Palpable content.
- Contexts in which this element can be used:
- Where phrasing content is expected.
- Content model:
- Zero or more
option
,optgroup
, and script-supporting elements. - Tag omission in text/html:
- Neither tag is omissible
- Content attributes:
- Global attributes
autofocus
- Automatically focus the form control when the page is loadeddisabled
- Whether the form control is disabledform
- Associates the control with aform
elementmultiple
- Whether to allow multiple valuesname
- Name of form control to use for §4.10.21 Form submission and in theform.elements
APIrequired
- Whether the control is required for §4.10.21 Form submissionsize
- Size of the control- Allowed ARIA role attribute values:
listbox
(default - do not set) ormenu
.- Allowed ARIA state and property attributes:
- Global aria-* attributes
- Any
aria-*
attributes applicable to the allowed roles. - DOM interface:
-
interface HTMLSelectElement : HTMLElement { attribute DOMString autocomplete; attribute boolean autofocus; attribute boolean disabled; readonly attribute HTMLFormElement? form; attribute boolean multiple; attribute DOMString name; attribute boolean _required; attribute unsigned long size; readonly attribute DOMString type; [SameObject] readonly attribute HTMLOptionsCollection options; attribute unsigned long length; getter Element? item(unsigned long index); HTMLOptionElement? namedItem(DOMString name); void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null); void remove(); // ChildNode overload void remove(long index); setter void (unsigned long index, HTMLOptionElement? option); [SameObject] readonly attribute HTMLCollection selectedOptions; attribute long selectedIndex; attribute DOMString value; readonly attribute boolean willValidate; readonly attribute ValidityState validity; readonly attribute DOMString validationMessage; boolean checkValidity(); boolean reportValidity(); void setCustomValidity(DOMString error); [SameObject] readonly attribute NodeList labels; };
The select
element represents a control for selecting amongst a set of
options.
The multiple
attribute is a boolean
attribute. If the attribute is present, then the select
element represents a control for selecting zero or more options from the list of options. If the attribute is absent, then the select
element represents a control for selecting a single option from
the list of options.
The size
attribute gives the number of options
to show to the user. The size
attribute, if specified, must
have a value that is a valid non-negative integer greater than zero.
The display size of a select
element is the
result of applying the rules for parsing non-negative integers to the value of
element’s size
attribute, if it has one and parsing it is
successful. If applying those rules to the attribute’s value is not successful,
or if the size
attribute is absent,
then the element’s display size is 4 if the element’s multiple
content attribute is present, and 1 otherwise.
The list of options for a select
element consists of all the option
element children of the select
element, and all the option
element children of all the optgroup
element
children of the select
element, in tree order.
The required
attribute is a boolean
attribute. When specified, the user will be required to select a value before submitting
the form.
If a select
element has a required
attribute specified, does not have a multiple
attribute
specified, and has a display size of 1; and if the value of the first option
element in the select
element’s list of options (if
any) is the empty string, and that option
element’s parent node is the select
element (and not an optgroup
element), then that option
is the select
element’s placeholder label option.
If a select
element has a required
attribute specified, does not have a multiple
attribute
specified, and has a display size of 1, then the select
element must have a placeholder label option.
In practice, the requirement stated in the paragraph above can only apply when a select
element does not have a sizes
attribute
with a value greater than 1.
Constraint validation: If the element has its required
attribute specified, and either none of the option
elements in the select
element’s list of options have their selectedness set to true, or the only option
element in the select
element’s list of options with its selectedness set to true is the placeholder label option,
then the element is suffering from being missing.
If the multiple
attribute is absent, and the element
is not disabled, then the user agent should allow the
user to pick an option
element in its list
of options that is itself not disabled. Upon
this option
element being picked (either
through a click, or through unfocusing the element after changing its value, or through a menu command, or through any other mechanism), and before the
relevant user interaction event is queued (e.g., before the click
event), the user agent must set the selectedness of the picked option
element
to true, set its dirtiness to true, and then send select
update notifications.
If the multiple
attribute is absent, whenever an option
element in the select
element’s list of options has its selectedness set to true, and whenever an option
element with its selectedness set to true is added to the select
element’s list of options,
the user agent must set the selectedness of all
the other option
elements in its list of
options to false.
If the multiple
attribute is absent and the
element’s display size is greater than 1, then the user
agent should also allow the user to request that the option
whose selectedness is true, if any, be unselected. Upon this
request being conveyed to the user agent, and before the relevant user interaction event is queued (e.g., before the click
event), the user agent must set the selectedness of that option
element to
false, set its dirtiness to true, and then send select
update notifications.
If nodes are inserted or nodes are removed causing the list of options to gain or lose one or more option
elements, or if an option
element in the list of options asks for a reset, then, if the select
element’s multiple
attribute is absent, the user agent must run the
first applicable set of steps from the following list:
- If the
select
element’s display size is 1, and nooption
elements in theselect
element’s list of options have their selectedness set to true - Set the selectedness of the first
option
element in the list of options in tree order that is not disabled, if any, to true. - If two or more
option
elements in theselect
element’s list of options have their selectedness set to true - Set the selectedness of all but the last
option
element with its selectedness set to true in the list of options in tree order to false.
If the multiple
attribute is present, and the
element is not disabled, then the user agent should
allow the user to toggle the selectedness of the option
elements in
its list of options that are themselves not disabled. Upon such an element being toggled (either through a click, or through a menu command, or any other mechanism), and before the
relevant user interaction event is queued (e.g., before a related click
event),
the selectedness of the option
element must
be changed (from true to false or false to true), the dirtiness of the element must be set to true, and the
user agent must send select
update notifications.
When the user agent is to send select
update notifications, queue a task to first fire a simple event that bubbles named input
at the select
element, and then fire a simple event that bubbles named change
at the select
element, using the user interaction task source as the task
source. If the JavaScript execution context stack was not empty when the user agent was
to send select
update notifications, then the resulting input
and change
events must not be trusted.
The reset algorithm for select
elements is to go through all the option
elements in the element’s list of options, set their selectedness to true if the option
element has a selected
attribute, and false otherwise,
set their dirtiness to false, and then have the option
elements ask for a reset.
The form
attribute is used to explicitly associate the select
element with its form owner.
The name
attribute represents the element’s name.
The disabled
attribute is used to make the control non-interactive and to prevent its value from being submitted.
The autofocus
attribute controls focus.
The autocomplete
attribute controls how the user agent provides autofill behavior.
A select
element that is not disabled is mutable.
- select .
type
-
Returns "
select-multiple
" if the element has amultiple
attribute, and "select-one
" otherwise. - select .
options
-
Returns an
HTMLOptionsCollection
of the list of options. - select .
length
[ = value ] -
Returns the number of elements in the list of options.
When set to a smaller number, truncates the number of
option
elements in theselect
.When set to a greater number, adds new blank
option
elements to theselect
. - element = select .
item
(index) - select[index]
-
Returns the item with index index from the list of options. The items are sorted in tree order.
- element = select .
namedItem
(name) -
Returns the first item with ID or
name
name from the list of options.Returns null if no element with that ID could be found.
- select .
add
(element [, before ] ) -
Inserts element before the node given by before.
The before argument can be a number, in which case element is inserted before the item with that number, or an element from the list of options, in which case element is inserted before that element.
If before is omitted, null, or a number out of range, then element will be added at the end of the list.
This method will throw a
HierarchyRequestError
exception if element is an ancestor of the element into which it is to be inserted. - select .
selectedOptions
-
Returns an
HTMLCollection
of the list of options that are selected. - select .
selectedIndex
[ = value ] -
Returns the index of the first selected item, if any, or -1 if there is no selected item.
Can be set, to change the selection.
- select .
value
[ = value ] -
Returns the value of the first selected item, if any, or the empty string if there is no selected item.
Can be set, to change the selection.
The type
IDL attribute, on getting, must
return the string "select-one
" if the multiple
attribute is absent, and the string "select-multiple
" if the multiple
attribute is present.
The options
IDL attribute must return an HTMLOptionsCollection
rooted at the select
node, whose filter matches
the elements in the list of options.
The options
collection is also mirrored on the HTMLSelectElement
object. The supported property indices at any instant
are the indices supported by the object returned by the options
attribute at that instant.
The length
IDL attribute must return the
number of nodes represented by the options
collection. On setting, it must act like the attribute
of the same name on the options
collection.
The item(index)
method
must return the value returned by the method of the same
name on the options
collection, when invoked with
the same argument.
The namedItem(name)
method must return the value returned by the
method of the same name on the options
collection,
when invoked with the same argument.
When the user agent is to set the value of a new
indexed property for a given property index index to a new value value, it must instead set the
value of a new indexed property with the given property index index to
the new value value on the options
collection.
Similarly, the add()
method must act like its
namesake method on that same options
collection.
The remove()
method must act like its
namesake method on that same options
collection when it
has arguments, and like its namesake method on the ChildNode
interface implemented by
the HTMLSelectElement
ancestor interface Element
when it has no
arguments.
The selectedOptions
IDL attribute
must return an HTMLCollection
rooted at the select
node, whose filter
matches the elements in the list of options that
have their selectedness set to true.
The selectedIndex
IDL attribute, on
getting, must return the index of the first option
element in the list of
options in tree order that has its selectedness set to true, if any. If there isn’t one,
then it must return -1.
On setting, the selectedIndex
attribute must set
the selectedness of all the option
elements in the list of options to false, and
then the option
element in the list of
options whose index is the given new value, if
any, must have its selectedness set to true and
its dirtiness set to true.
This can result in no element having a selectedness set to true even in the case of the select
element having no multiple
attribute and a display size of 1.
The value
IDL attribute, on getting, must
return the value of the first option
element in the list of options in tree
order that has its selectedness set to
true, if any. If there isn’t one, then it must return the empty string.
On setting, the value
attribute must set the selectedness of all the option
elements
in the list of options to false, and then the
first option
element in the list of
options, in tree order, whose value is equal to the given new value, if any, must have its selectedness set to true and its dirtiness set to true.
This can result in no element having a selectedness set to true even in the case of the select
element having no multiple
attribute and a display size of 1.
The multiple
, required
, and size
IDL attributes must reflect the
respective content attributes of the same name. The size
IDL
attribute has a default value of zero.
For historical reasons, the default value of the size
IDL attribute does not return the actual size used, which, in
the absence of the size
content attribute, is either 1 or 4
depending on the presence of the multiple
attribute.
The willValidate
, validity
, and validationMessage
IDL attributes, and
the checkValidity()
, reportValidity()
, and setCustomValidity()
methods, are part of
the constraint validation API.
The labels
IDL attribute provides a list of the element’s label
s.
The autofocus
, disabled
, form
, and name
IDL attributes are part of the
element’s forms API.
select
element can be used to offer the user
with a set of options from which the user can select a single option. The default option is
preselected.
<div> <label for="unittype">Select unit type:</label> <select id="unittype" name="unittype"> <option value="1"> Miner </option> <option value="2"> Puffer </option> <option value="3" selected> Snipey </option> <option value="4"> Max </option> <option value="5"> Firebot </option> </select> </div>
When there is no default option, a value that provides instructions or a hint (placeholder option) can be used instead:
<select name="unittype" required> <option value=""> Select unit type </option> <option value="1"> Miner </option> <option value="2"> Puffer </option> <option value="3"> Snipey </option> <option value="4"> Max </option> <option value="5"