Support in all current engines.
This section is non-normative.
表单是一种网页组件,可以包含表单控件如文本,按钮,复选框,范围或颜色选择器控件。 用户可以与这样的表单进行交互并提供数据,随后这些数据被发送到服务器用于进一步处理 (例如返回搜索或计算结果)。在许多情况下都不需要客户端脚本,尽管提供了这样的 API, 脚本可以用这些 API 增强用户体验,或者将表单用于提交数据之外的用途。
编写一个表单包含几个步骤,可以按任意顺序进行: 编写用户界面,实现服务器端处理以及配置用户界面以与服务器进行通信。
This section is non-normative.
为了这个简短的介绍,我们将创建一个 Pizza 订购表单。
表单都以 form
元素开始,其中可以放置一些控件。
多数控件都由 input
元素表示,它默认提供一个文本控件。
使用 label
元素来描述控件;标签文本和控件自己都会进入
label
元素内。表单的每一部分都是一个
段落,一般会用 p
元素来与其他部分分隔。
放到一起,可以这样询问顾客的名字:
<form> <p><label>Customer name: <input></label></p> </form>
为了让用户选择 Pizza 的大小,我们可以使用一组单选按钮。
单选按钮也是用 input
元素,这次设置一个 type
属性,值为 radio
。
为了让单选按钮成组,要使用 name
属性给它们一样的名字。
为了让一批控件成为一组,比如这个例子中的单选按钮,可以使用
fieldset
元素。这样的控件组的标题由 fieldset
中的第一个元素给出,
这个元素必须是一个 legend
元素。
<form> <p><label>Customer name: <input></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> </form>
我们高亮了上一个步骤中的改变。
我们可以使用复选框来选择配料。这些复选框也使用 input
元素,
它们的 type
属性值为 checkbox
:
<form> <p><label>Customer name: <input></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> </form>
这个 pizza 店总会犯一些错误,因此需要顾客的联系方式。
为此我们可以使用电话号码的表单控件(type
属性设为
tel
的 input
元素),
以及 e-mail 地址(type
属性设为
email
的 input
元素):
<form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> </form>
我们可以使用 type
属性设为
time
的 input
元素来询问配送时间。
很多控件都可以设置可选值的范围;这个例子中我们关心的属性是
min
, max
和
step
。这些属性分别用来设置最小时间,最大时间,
以及允许的值之间的间隔(单位为秒)。这个 pizza 店只在 11am 到 9pm 之间配送,
而且不保证精确到 15 分钟以内,我们可以这样写:
<form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p> </form>
textarea
元素可以用来提供多行文本。例如我们要用它来给顾客提供一个地方,编写配送备注:
<form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p> <p><label>Delivery instructions: <textarea></textarea></label></p> </form>
最后,为了让表单可以提交我们要用一个 button
元素:
<form> <p><label>Customer name: <input></label></p> <p><label>Telephone: <input type=tel></label></p> <p><label>E-mail address: <input type=email></label></p> <fieldset> <legend> Pizza Size </legend> <p><label> <input type=radio name=size> Small </label></p> <p><label> <input type=radio name=size> Medium </label></p> <p><label> <input type=radio name=size> Large </label></p> </fieldset> <fieldset> <legend> Pizza Toppings </legend> <p><label> <input type=checkbox> Bacon </label></p> <p><label> <input type=checkbox> Extra Cheese </label></p> <p><label> <input type=checkbox> Onion </label></p> <p><label> <input type=checkbox> Mushroom </label></p> </fieldset> <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p> <p><label>Delivery instructions: <textarea></textarea></label></p> <p><button>Submit order</button></p> </form>
This section is non-normative.
编写服务器端处理程序的具体的细节超出了本规范的范围。
这个概述中我们会假设
https://pizza.example.com/order.cgi
处的脚本已经配置为接受
application/x-www-form-urlencoded
格式的表单提交,
而且 HTTP POST 消息体中会包含以下参数:
custname
custtel
custemail
size
small
, medium
或 large
topping
bacon
, cheese
, onion
和 mushroom
delivery
comments
This section is non-normative.
表单提交以多种方式暴露给服务器,通常是 HTTP GET 或 POST 请求。
在 form
元素上使用 method
属性来指定使用哪种方法。
这还没有指定表单数据的编码方式,指定编码方式要使用 enctype
属性。你还需要使用 action
属性来指定
处理提交的数据的服务的 URL。
每个需要提交的表单控件都要有一个名字来对应提交的数据。
我们已经为单选按钮组指定了名字;这个属性(name
)也指定了提交的名字。
单选按钮可以之间可以通过(使用 value
属性)
给它们不同的值来区分。
多个控件可以有同样的名字;例如我们给所有复选框一样的名字,服务器检查那个名字的哪些值提交了上来。
— 像单选按钮一样,也通过 value
属性给它们不重复的值。
鉴于上一小节的设置,表单现在变成了:
<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>
有些属性的值用引号包含,有些没有,但这没有特别的含义。 HTML 语法允许很多种合法的方式来指定属性,如 语法部分 所述。
例如,如果顾客输入 "Denise Lawrence" 作为名字,"555-321-8642" 作为电话号,没有指定 e-mail 地址, 要一个中等大小的 Pizza,选择了 Extra Cheese 和 Mushroom 配料, 输入的配送时间是 7pm 并在配送备注部分留空,用户代理会提交下面内容到在线 Web 服务:
custname=Denise+Lawrence&custtel=555-321-8642&custemail=&size=medium&topping=cheese&topping=mushroom&delivery=19%3A00&comments=
Support in all current engines.
This section is non-normative.
可以通过表单标记使得用户代理可以在表单提交之前检查用户输入。 服务器仍然必须校验输入是有效的(因为恶意用户可以很容易绕过表单验证), 但这使我们可以避免因为只能在服务器上检查而造成用户等待。
最简单的标记是 required
属性,
可以在 input
元素上指定,表示只有给出值之后表单才可以提交。
把这个属性添加到顾客名字、Pizza 大小和配送时间字段,在用户没填写这些字段就提交表单时,
我们可以让用户代理提示用户。
<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>
也可以使用 maxlength
属性来限制输入的长度。
把这个属性添加到 textarea
元素上,我们可以限制用户输入到 1000 字符,
防止他们给配送员编写长文而不聚焦重点。
<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>
提交表单时,每个不合法的表单控件上,以及 form
元素上都会触发
invalid
事件,
这个事件可以用来显示表单存在哪些问题的一个描述,因为浏览器自己只会逐个报告问题。
This section is non-normative.
有些浏览器尝试帮助用户自动填充表单控件,避免让用户每次重新输入。例如询问用户电话号码的字段就可以自动填充为用户的手机号码。
为了帮助用户代理做自动填充,可以使用 autocomplete
属性来描述字段的用途。下面这个表单的例子,Pizza 配送的用户信息中三个字段都可以这样自动填充:
添加相应的信息后看起来是这样的:
<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>
This 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 inputmode
attribute we can select appropriate
input modalities:
<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>Buzzer code: <input name="custbuzz" inputmode="numeric"></label></p>
<p><label>Email 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>
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:
<p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel"></label>
<p><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
):
<p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel-national"></label>
<p><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 text control (<input type=text>
), a drop-down list (<select>
), radio buttons (<input
type=radio>
), etc. It only depends on what kind of interface is desired.
Finally, 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
.
<p><label>Japanese name: <input name="j" type="text" autocomplete="section-jp name"></label>
<label>Romanized name: <input name="e" type="text" autocomplete="section-en 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.
Separate from the choices regarding type
and autocomplete
, the inputmode
attribute decides what kind of input modality (e.g.,
virtual keyboard) to use, when the control is a text control.
Consider credit card numbers. The appropriate input type is not <input type=number>
, as explained below; it is instead <input type=text>
. To encourage the user agent to use a
numeric input modality anyway (e.g., a virtual keyboard displaying only digits), the page would
use
<p><label>Credit card number:
<input name="cc" type="text" inputmode="numeric" pattern="[0-9]{8,19}" autocomplete="cc-number">
</label></p>
This section is non-normative.
这个 Pizza 配送的例子中,时间的格式为 "HH:MM": 两位数字的小时(24小时格式),以及两位数字的时间。 (还可以指定秒,虽然这个例子中没有必要)
但是在某些时区里展示给用户的时间是不同的。例如在美国仍然经常使用 12 小时的表加一个 am/pm 指示, 比如 "2pm"。在法国通常使用一个 "h" 字符来分隔小时和分钟,例如 "14h00"。
日期也存在类似的问题,更严重的是日期各部分的顺序也总是不一致的。 — 例如在 Cyprus 2003 年 2 月 1 日会写成 "1/2/03", 同样的日期在日本会写成 "2003年02月01日" — 数字也是一样, 在不同的时区小数点和千分点使用的标点也不一样。
因此把 HTML 和表单提交中的时间、日期和数字的格式(即本规范中定义的格式,以及 ISO 8601 标准建立的对计算机可读的时间和日期格式),和 浏览器显示给用户的或浏览器接受用户输入的时间、日期和数字格式区分开来非常重要。
协议中(即 HTML 标记和表单提交)使用的格式是为了使得计算机可读和一致,且与用户的区域设置无关。 例如日期总是表示为 "YYYY-MM-DD",比如 "2003-02-01"。用户永远不应该看到这个格式。
页面给出的时间、日期或数字的按照协议的格式会在显示给用户之前翻译成用户偏好的显示方式 (基于用户偏好或页面自己所在的区域设置)。类似地,在用户使用他们偏好的格式输入时间、日期或数字时, 用户代理把它放回 DOM 或提交之前,要把它转换回协议格式。
这使得页面脚本和服务器可以使用一致的方式来处理时间、日期和数字,不需要支持几十种不同的格式, 同时仍然能够支持用户的需要。
关于表单控件的本地化请参考 实现纪要。
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:
Denotes elements that are listed in the form.elements
and fieldset.elements
APIs. These elements also
have a form
content attribute, and a matching form
IDL attribute, that allow authors to specify an explicit
form owner.
Denotes elements that can be used for constructing the entry list 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.
Denotes elements that can be affected when a form
element is reset.
Denotes elements that inherit the autocapitalize
attribute from their 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.
button
input
(if the type
attribute is not in the state)meter
output
progress
select
textarea
form
elementSupport in all current engines.
Support in all current engines.
form
element descendants.accept-charset
— Character encodings to use for form submissionaction
— URL to use for form submissionautocomplete
— Default setting for autofill feature for controls in the formenctype
— Entry list encoding type to use for form submissionmethod
— Variant to use for form submissionname
— Name of form to use in the document.forms
APInovalidate
— Bypass form control validation for form submissiontarget
— Browsing context for form submissionrel
[Exposed=Window,
LegacyOverrideBuiltIns,
LegacyUnenumerableNamedProperties]
interface HTMLFormElement : HTMLElement {
[HTMLConstructor] constructor();
[CEReactions] attribute DOMString acceptCharset;
[CEReactions] attribute USVString action;
[CEReactions] attribute DOMString autocomplete;
[CEReactions] attribute DOMString enctype;
[CEReactions] attribute DOMString encoding;
[CEReactions] attribute DOMString method;
[CEReactions] attribute DOMString name;
[CEReactions] attribute boolean noValidate;
[CEReactions] attribute DOMString target;
[CEReactions] attribute DOMString rel;
[SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
[SameObject] readonly attribute HTMLFormControlsCollection elements;
readonly attribute unsigned long length;
getter Element (unsigned long index);
getter (RadioNodeList or Element) (DOMString name);
undefined submit();
undefined requestSubmit(optional HTMLElement? submitter = null);
[CEReactions] undefined reset();
boolean checkValidity();
boolean reportValidity();
};
The form
element represents a hyperlink that can be
manipulated through 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
attribute gives the character
encodings that are to be used for the submission. If specified, the value must be an ASCII
case-insensitive match for "UTF-8
". [ENCODING]
The name
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
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 and the invalid value default are 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
, 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.
elements
Support in all current engines.
Returns an HTMLFormControlsCollection
of the form controls in the form (excluding image
buttons for historical reasons).
length
Support in all current engines.
Returns the number of form controls in the form (excluding image buttons for historical reasons).
Returns the indexth element in the form (excluding image buttons for historical reasons).
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.
submit
()Support in all current engines.
Submits the form, bypassing interactive
constraint validation and without firing a submit
event.
requestSubmit
( [ submitter ] )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.
reset
()Support in all current engines.
Resets the form.
checkValidity
()Returns true if the form's controls are all valid; otherwise, returns false.
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.
Support in all current engines.
The name
and
rel
IDL attributes must reflect the
content attribute of the same name.
Support in all current engines.
The acceptCharset
IDL attribute must
reflect the accept-charset
content
attribute.
The relList
IDL attribute must
reflect the rel
content attribute.
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, when invoked, must submit the form
element from the form
element itself, with the submitted from submit()
method flag set.
The requestSubmit(submitter)
method, when invoked, must run the following steps:
If submitter is not null, then:
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 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.
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.
label
elements.for
— Associate the label with form control[Exposed=Window]
interface HTMLLabelElement : HTMLElement {
[HTMLConstructor] constructor();
readonly attribute HTMLFormElement? form;
[CEReactions] 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 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 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>
control
Support in all current engines.
Returns the form control that is associated with this element.
form
Support 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.
Support in all current engines.
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.
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.
labels
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.
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 state, in which case it
must instead return null.
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>