GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||
GeezerVison is showing html.spec.whatwg.org — HTML Standard
4.10 FormsSupport in all current engines. Firefox4+Safari4+Chrome61+ Opera52+Edge79+ Edge (Legacy)16+Internet Explorer10+ Firefox Android5+Safari iOS3.2+Chrome Android61+WebView Android61+Samsung Internet8.0+Opera Android47+ 4.10.1 IntroductionThis section is non-normative. A form is a component of a web page that has form controls, such as text, buttons, checkboxes, range, or color picker controls. 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 interfaceThis section is non-normative. For the purposes of this brief introduction, we will create a pizza ordering form. Any form starts with a
To let the user select the size of the pizza, we can use a set of radio buttons. Radio buttons
also use the
Changes from the previous step are highlighted. To pick toppings, we can use checkboxes. These use the
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 (
We can use an
The
Finally, to make the form submittable we use the
4.10.1.2 Implementing the server-side processing for a formThis 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
4.10.1.3 Configuring a form to communicate with a serverThis 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 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 ( 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 Given the settings in the previous section, this all becomes:
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 the syntax section. For example, if the customer entered "Denise Lawrence" as their name, "555-321-8642" as their telephone number, did not specify an email 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 control blank, the user agent would submit the following to the online web service:
4.10.1.4 Client-side form validationSupport in all current engines. Firefox4+Safari5+Chrome4+ Opera≤12.1+Edge79+ Edge (Legacy)12+Internet Explorer10+ Firefox Android?Safari iOS4+Chrome Android?WebView Android≤37+Samsung Internet?Opera Android≤12.1+ 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
It is also possible to limit the length of the input, using the
When a form is submitted, 4.10.1.5 Enabling client-side automatic filling of form controlsThis 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
4.10.1.6 Improving the user experience on mobile devicesThis section is non-normative. Some devices, in particular those with virtual keyboards 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
4.10.1.7 The difference between the field type, the autofill field name, and the input modalityThis section is non-normative. The The The First, consider telephone numbers. If a page is asking for a telephone number from the user,
the right form control to use is 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:
But if the site only supports British customers and recipients, it might instead look like this
(notice the use of
Now, consider a person's preferred languages. The right Finally, consider names. If a page just wants one name from the user, then the relevant control
is
In this example, the " The " Separate from the choices regarding Consider credit card numbers. The appropriate input type is not
4.10.1.8 Date, time, and number formatsThis 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 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". While some users might see this format, others might see it as "01.02.2003" or "February 1, 2003". 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. 4.10.2 CategoriesMostly 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:
Some elements, not all of them form-associated,
are categorized as labelable elements. These are elements that
can be associated with a
4.10.3 The |
| Keyword | State | Brief description |
|---|---|---|
on
| On | Form controls will have their autofill field name set to "on" by default.
|
off
| Off | Form controls will have their autofill field name set to "off" by default.
|
The attribute's missing value default and invalid value default are both the On state.
The action, enctype,
method, novalidate,
and target attributes are attributes for form
submission.
The rel attribute on
form elements controls what kinds of links the elements create. The attribute's value
must be a unordered set of unique space-separated tokens. The allowed keywords and their meanings are defined in an earlier section.
rel's supported
tokens are the keywords defined in HTML link types which are
allowed on form elements, impact the processing model, and are supported by the user
agent. The possible supported tokens are noreferrer, noopener, and opener. rel's supported tokens must only include the tokens from this
list that the user agent implements the processing model for.
form.elementsSupport in all current engines.
Returns an HTMLFormControlsCollection of the form controls in the form
(excluding image buttons for historical reasons).
form.lengthSupport in all current engines.
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 or name (excluding image buttons for historical reasons); or, if there
are none, returns the img 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 the tree.
If there are multiple matching items, then a RadioNodeList object containing all
those elements is returned.
form.submit()Support in all current engines.
Submits the form, bypassing interactive
constraint validation and without firing a submit
event.
form.requestSubmit([ submitter ])Support in all current engines.
Requests to submit the form. Unlike submit(), this
method includes interactive constraint
validation and firing a submit event, either of which
can cancel submission.
The submitter argument can be used to point to a specific submit button, whose formaction, formenctype, formmethod, formnovalidate, and formtarget attributes can impact submission. Additionally,
the submitter will be included when constructing the entry list for submission;
normally, buttons are excluded.
form.reset()Support in all current engines.
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 elements
IDL attribute must return an HTMLFormControlsCollection rooted at the
form element's root, 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.
To determine the value of an indexed property for a
form element, 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 any
input elements whose type attribute is in the
Image Button state:
If candidate has an id attribute, add
an entry to sourced names with that id
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 that name attribute's value as the string, candidate
as the element, and name as the source.
For each img element candidate whose form owner is the
form element:
If candidate has an id attribute, add
an entry to sourced names with that id
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 that name attribute's value as the string, candidate
as the element, and name as the source.
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.
To determine the value of a named property name
for a form element, the user agent must run the following steps:
Let candidates be a live RadioNodeList object
containing all the listed elements, whose form
owner is the form element, that have either an id attribute or a name attribute equal
to name, with the exception of input elements whose type attribute is in the Image Button state, in tree order.
If candidates is empty, let candidates be a live
RadioNodeList object containing all the img elements, whose form
owner is the form element, that have either an id attribute or a name 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.
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 steps are to submit this from
this, with submitted from submit() method set to true.
The requestSubmit(submitter) method, when
invoked, must run the following steps:
If submitter is not null:
If submitter is not a submit
button, then throw a TypeError.
If submitter's form owner is not this form element,
then throw a "NotFoundError" DOMException.
Otherwise, set submitter to this form element.
The reset()
method, when invoked, must run the following steps:
If the form element is marked as locked for reset, then return.
Mark the form element as locked for reset.
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 returned 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 returned a positive result, and false if it returned
a negative result.
This example shows two search forms:
< 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 >
label elementSupport in all current engines.
Support in all current engines.
Support in all current engines.
label elements.for — Associate the label with form control
[Exposed =Window ]
interface HTMLLabelElement : HTMLElement {
[HTMLConstructor ] constructor ();
readonly attribute HTMLFormElement ? form ;
[CEReactions , Reflect="for"] 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.
Support in all current engines.
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 tree as the
label element. If the attribute is specified and there is an element in
the tree whose ID is equal to the value of the for attribute, and the first such element in tree
order is a labelable element, then that element is the
label element's labeled control.
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 exact default presentation and behavior, in particular what
its activation behavior might be, if anything, should match the platform's label
behavior. The activation behavior of a label element for events targeted
at interactive content descendants of a label element, and any
descendants of those interactive content descendants, must be to do nothing.
Form-associated custom
elements are labelable elements, so for user agents
where the label element's activation behavior impacts the labeled
control, both built-in and custom elements will be impacted.
For example, on platforms where clicking a label activates the form control, clicking the
label in the following snippet could trigger the user agent to fire a click event at the input element, as if the
element itself had been triggered by the user:
< label >< input type = checkbox name = lost > Lost</ label >
Similarly, assuming my-checkbox was declared as a
form-associated custom element (like in this
example), then the code
< label >< my-checkbox name = lost ></ my-checkbox > Lost</ label >
would have the same behavior, firing a click event at the my-checkbox
element.
On other platforms, the behavior in both cases might be just to focus the control, or to do nothing.
The following example shows three form controls each with a label, two of which have small text showing the right format for users to use.
< 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.controlSupport in all current engines.
Returns the form control that is associated with this element.
label.formSupport in all current engines.
Returns the form owner of the form control that is associated with this element.
Returns null if there isn't one.
The control
IDL attribute must return the label element's labeled control, if any,
or null if there isn't one.
The form IDL
attribute must run the following steps:
If the label element has no labeled control, then return
null.
If the label element's labeled control is not a
form-associated element, then return null.
Return the label element's labeled control's form
owner (which can still be null).
The form IDL attribute on the
label element is different from the form IDL
attribute on listed form-associated elements, and the label element does not have a form content attribute.
control.labelsSupport in all current engines.
Support in all current engines.
Support in all current engines.
Support in all current engines.
Support in all current engines.
Support in all current engines.
Support in all current engines.
Returns a NodeList of all the label elements that the form control
is associated with.
Labelable elements and all input elements
have a live 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 that are not form-associated custom elements, and the labels IDL attribute of input elements, on getting,
must return that NodeList object, and that same value must always be returned, unless
this element is an input element whose type
attribute is in the Hidden state, in which case it
must instead return null.
Support in all current engines.
Form-associated custom elements don't have
a labels IDL attribute. Instead, their
ElementInternals object has a labels IDL attribute. On getting, it must throw
a "NotSupportedError" DOMException if the target element is not a form-associated custom
element. Otherwise, it must return that NodeList object, and that same value
must always be returned.
This (non-conforming) example shows what happens to the NodeList and what labels returns when an input element has its type attribute changed.
<!doctype html>
< p >< label >< input ></ label ></ p >
< script >
const input = document. querySelector( 'input' );
const labels = input. labels;
console. assert( labels. length === 1 );
input. type = 'hidden' ;
console. assert( labels. length === 0 ); // the input is no longer the label's labeled control
console. assert( input. labels === null );
input. type = 'checkbox' ;
console. assert( labels. length === 1 ); // the input is once again the label's labeled control
console. assert( input. labels === labels); // same value as returned originally
</ script >