--- title: :输入(表单输入)元素 slug: Web/HTML/Element/Input tags: - Element - Forms - HTML - HTML forms - HTML input tag - Input - Reference - Web translation_of: Web/HTML/Element/input ---
{{HTMLRef}}
HTML <input>
元素用于为基于 Web 的表单创建交互式控件,以便接受来自用户的数据; 可以使用各种类型的输入数据和控件小部件,具体取决于设备和{{Glossary("user agent")}}。
{{EmbedInteractiveExample("pages/tabbed/input-text.html", "tabbed-shorter")}}
内容分类 | 流动区域; 内容区域; 交互式内容(如果不是处于hiddenhidden 状态); 列表,可标签,可提交,可重置,与表单相关的元素。 |
---|---|
允许的内容 | 无,这是一个{{Glossary("empty element","空元素")}}。 |
标签省略 |
必须有开始标签但不必有结束标签。 |
允许的祖先元素 | 任何元素都可以包含语句型元素。 |
允许的无障碍网络应用 |
|
DOM 接口 | {{domxref("HTMLInputElement")}} |
<input>
types<input>
的工作方式相当程度上取决于{{htmlattrxref("type", "input")}}属性的值,不同的 type 值会在各自的参考页中进行介绍。如果未指定此属性,则采用的默认类型为 text
。
可用的值包括:
Type | 描述 | 基础例子 | Spec |
---|---|---|---|
{{HTMLElement("input/button", "button")}} | 没有默认行为的按钮,上面显示 {{anch('value')}} 属性的值,默认为空。 | {{EmbedLiveSample("examplebutton",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/checkbox", "checkbox")}} | 复选框,可设为选中或未选中。 | {{EmbedLiveSample("examplecheckbox",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/color", "color")}} | 用于指定颜色的控件;在支持的浏览器中,激活时会打开取色器。 | {{EmbedLiveSample("examplecolor",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/date", "date")}} | 输入日期的控件(年、月、日,不包括时间)。在支持的浏览器激活时打开日期选择器或年月日的数字滚轮。 | {{EmbedLiveSample("exampledate",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/datetime-local", "datetime-local")}} | 输入日期和时间的控件,不包括时区。在支持的浏览器激活时打开日期选择器或年月日的数字滚轮。 | {{EmbedLiveSample("exampledtl",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/email", "email")}} | 编辑邮箱地址的区域。类似 text 输入,但在支持的浏览器和带有动态键盘的设备上会有确认参数和相应的键盘。 |
{{EmbedLiveSample("exampleemail",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/file", "file")}} | 让用户选择文件的控件。使用{{anch('accept')}}属性规定控件能选择的文件类型。 | {{EmbedLiveSample("examplefile",'100%',55,"","", "nobutton")}} | |
{{HTMLElement("input/hidden", "hidden")}} | 不显示的控件,其值仍会提交到服务器。举个例子,右边就是一个隐形的控件。 | ||
{{HTMLElement("input/image", "image")}} | 带图像的 submit 按钮。显示的图像由 src 属性规定。如果 {{anch('src')}} 缺失,{{anch('alt')}} 属性就会显示。 |
{{EmbedLiveSample("exampleimage",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/month", "month")}} | 输入年和月的控件,没有时区。 | {{EmbedLiveSample("examplemonth",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/number", "number")}} | 用于输入数字的控件。如果支持的话,会显示滚动按钮并提供缺省验证(即只能输入数字)。拥有动态键盘的设备上会显示数字键盘。 | {{EmbedLiveSample("examplenumber",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/password", "password")}} | 单行的文本区域,其值会被遮盖。如果站点不安全,会警告用户。 | {{EmbedLiveSample("examplepassword",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/radio", "radio")}} | 单选按钮,允许在多个拥有相同 {{anch('name')}} 值的选项中选中其中一个。 | {{EmbedLiveSample("exampleradio",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/range", "range")}} | 此控件用于输入不需要精确的数字。控件是一个范围组件,默认值为正中间的值。同时使用{{anch('htmlattrdefmin')}} 和 {{anch('htmlattrdefmax')}}来规定值的范围。 | {{EmbedLiveSample("examplerange",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/reset", "reset")}} | 此按钮将表单的所有内容重置为默认值。不推荐。 | {{EmbedLiveSample("examplereset",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/search", "search")}} | 用于搜索字符串的单行文字区域。输入文本中的换行会被自动去除。在支持的浏览器中可能有一个删除按钮,用于清除整个区域。拥有动态键盘的设备上的回车图标会变成搜索图标。 | {{EmbedLiveSample("examplesearch",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/submit", "submit")}} | 用于提交表单的按钮。 | {{EmbedLiveSample("examplesubmit",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/tel", "tel")}} | 用于输入电话号码的控件。拥有动态键盘的设备上会显示电话数字键盘。 | {{EmbedLiveSample("exampletel",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/text", "text")}} | 默认值。单行的文本区域,输入中的换行会被自动去除。 | {{EmbedLiveSample("exampletext",200,55,"","", "nobutton")}} | |
{{HTMLElement("input/time", "time")}} | 用于输入时间的控件,不包括时区。 | {{EmbedLiveSample("exampletime",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/url", "url")}} |
用于输入 URL 的控件。类似 |
{{EmbedLiveSample("exampleurl",200,55,"","", "nobutton")}} | {{HTMLVersionInline("5")}} |
{{HTMLElement("input/week", "week")}} | 用于输入以年和周数组成的日期,不带时区。 | {{EmbedLiveSample("exampleweek",200,55,"","", "nobutton")}} | |
废弃的值 | |||
{{HTMLElement("input/datetime", "datetime")}} | {{deprecated_inline}} {{obsolete_inline}} 用于输入基于 UTC 时区的日期和时间(时、分、秒及秒的小数部分)。 | {{EmbedLiveSample("exampledatetime",200,75,"","", "nobutton")}} |
<input>
元素由于拥有诸多属性而异常强大,其中前文举例说明的{{htmlattrxref("type", "input")}}属性尤其重要。由于所有<input>
元素,无论是哪种 type
,都基于{{domxref("HTMLInputElement")}}接口,所以理论上说,它们共享一套相同的属性。但实际上大部分属性只作用于特定一组 type
。此外,一些属性作用于<input>
的方式取决于<input>
的type
属性,不同的type
有不同的效果。
下面的表格列出了所有属性,每个属性都有简短的描述。表格后的列表更详细地描述了各个属性及它们与哪些<input>
type
相关。与大部分或者全部<input>
type
都相关的属性会讲述更多细节。一些针对特定<input>
type
的属性,或者所有<input>
type
都有,但在特定的<input>
type
上有特定表现的属性,会在相应的type
页面中说明。这个元素包含全局属性,一些针对<input>
元素有额外意义的全局属性也会特别说明。
属性 | 相关的 type | 描述 |
---|---|---|
{{anch('htmlattrdefaccept', 'accept')}} | file | 用于规定文件上传控件中期望的文件类型 |
{{anch('htmlattrdefalt', 'alt')}} | image | image type 的 alt 属性,是可访问性的要求。 |
{{anch('htmlattrdefautocomplete', 'autocomplete')}} | 所有 | 用于表单的自动填充功能 |
{{anch('htmlattrdefautofocus', 'autofocus')}} | 所有 | 页面加载时自动聚焦到此表单控件 |
{{anch('htmlattrdefcapture', 'capture')}} | file | 文件上传控件中媒体拍摄的方式 |
{{anch('htmlattrdefchecked', 'checked')}} | radio, checkbox | 用于控制控件是否被选中 |
{{anch('htmlattrdefdirname', 'dirname')}} | text, search | 表单区域的一个名字,用于在提交表单时发送元素的方向性 |
{{anch('htmlattrdefdisabled', 'disabled')}} | 所有 | 表单控件是否被禁用 |
{{anch('htmlattrdefform', 'form')}} | 所有 | 将控件和一个 form 元素联系在一起 |
{{anch('htmlattrdefformaction', 'formaction')}} | image, submit | 用于提交表单的 URL |
{{anch('htmlattrdefformenctype', 'formenctype')}} | image, submit | 表单数据集的编码方式,用于表单提交 |
{{anch('htmlattrdefformmethod', 'formmethod')}} | image, submit | 用于表单提交的 HTTP 方法 |
{{anch('htmlattrdefformnovalidate', 'formnovalidate')}} | image, submit | 提交表单时绕过对表单控件的验证 |
{{anch('htmlattrdefformtarget', 'formtarget')}} | image, submit | 表单提交的浏览上下文 |
{{anch('htmlattrdefheight', 'height')}} | image |
和 {{htmlelement('img')}} 的 |
{{anch('htmlattrdeflist', 'list')}} | 绝大部分 | 自动填充选项的{{htmlelement('datalist')}} 的 id 值 |
{{anch('htmlattrdefmax', 'max')}} | 数字 type | 最大值 |
{{anch('htmlattrdefmaxlength', 'maxlength')}} | password, search, tel, text, url | value 的最大长度(最多字符数目) |
{{anch('htmlattrdefmin', 'min')}} | 数字 type | 最小值 |
{{anch('htmlattrdefminlength', 'minlength')}} | password, search, tel, text, url | value 的最小长度(最少字符数目) |
{{anch('htmlattrdefmultiple', 'multiple')}} | email, file | 布尔值。 是否允许多个值 |
{{anch('htmlattrdefname', 'name')}} | 所有 | input 表单控件的名字。以名字/值对的形式随表单一起提交 |
{{anch('htmlattrdefpattern', 'pattern')}} | password, text, tel | 匹配有效 value 的模式(pattern) |
{{anch('htmlattrdefplaceholder', 'placeholder')}} | password, search, tel, text, url | 当表单控件为空时,控件中显示的内容 |
readonly | 绝大部分 | 布尔值。存在时表示控件的值不可编辑 |
required | 绝大部分 | 布尔值。表示此值为必填项或者提交表单前必须先检查该值 |
{{anch('htmlattrdefsize', 'size')}} | email, password, tel, text | 控件的大小 |
{{anch('htmlattrdefsrc', 'src')}} | image | 和{{htmlelement('img')}} 的 src 属性一样;图像资源的地址 |
{{anch('htmlattrdefstep', 'step')}} | 数字 type | 有效的递增值 |
{{anch('htmlattrdeftype', 'type')}} | 所有 | input 表单控件的 type |
{{anch('htmlattrdefvalue', 'value')}} | 所有 | 表单控件的值。以名字/值对的形式随表单一起提交 |
{{anch('htmlattrdefwidth', 'width')}} | image | 与 {{htmlelement('img')}} 的 width 属性一样 |
一些额外的非标准属性会在标准属性后面列出。
是 file
,则该属性表明了服务器端可接受的文件类型;否则它将被忽略。该属性的值必须为一个逗号分割的列表,包含了多个唯一的内容类型声明:
audio/*
表示音频文件 {{ HTMLVersionInline(5) }}video/*
表示视频文件 {{ HTMLVersionInline(5) }}image/*
表示图片文件 {{ HTMLVersionInline(5) }}off
: 用户必须手动填值,或者该页面提供了自己的自动补全方法。浏览器不对此字段自动填充。on
: 浏览器可以根据用户先前的填表情况对此字段自动填值。name
: 完整的姓名honorific-prefix:
Prefix or title (e.g. "Mr.", "Ms.", "Dr.", "Mlle")given-name
:名additional-name
family-name
:姓honorific-suffix
: Suffix (e.g. "Jr.", "B.Sc.", "MBASW", "II")nickname
email
username
new-password
: 新密码(如创建帐号或更改密码时使用)current-password
organization-title
: Job title (e.g. "Software Engineer", "Senior Vice President", "Deputy Managing Director")organization
street-address
address-line1, address-line2, address-line3, address-level4, address-level3, address-level2, address-level1
country
country-name
postal-code
cc-name
: Full name as given on the payment instrumentcc-given-name
cc-additional-name
cc-family-name
cc-number
: Code identifying the payment instrument (e.g. the credit card number)cc-exp:
Expiration date of the payment instrumentcc-exp-month
cc-exp-year
cc-csc
: Security code for the payment instrument cc-type
: Type of payment instrument (e.g. Visa)transaction-currency
transaction-amount
language
: Preferred language; Valid BCP 47 language tagbday
bday-day
bday-month
bday-year
sex
: Gender identity (e.g. Female, Fa'afafine); Free-form text, no newlinestel
url
: Home page or other Web page corresponding to the company, person, address, or contact information in the other fields associated with this fieldphoto
: Photograph, icon, or other image corresponding to the company, person, address, or contact information in the other fields associated with this field参考 WHATWG 标准 获取更多详细内容。
如果<input>
元素上没有autocomplete属性,浏览器可使用包含该 input 元素的表单(<form>
)或通过 input 的form属性指定的表单的autocomplete属性值。更多信息请参见{{ HTMLElement("form") }}的autocomplete
属性。
与其他浏览器不同,autocomplete 还控制着 Firefox 浏览器 对 <input> 持久化动态禁用状态和(如果适用)跨页面加载的动态检查。持久化特性默认是开启的。设置autocomplete的值为off 可以关闭该特性。即使 autocomplete 属性通常不应用于<input>的 type,它也可以工作。具体可以查看{{bug(654072)}}。
Introduced in the HTML Media Capture specification and valid for the file
input type only, the capture
attribute defines which media—microphone, video, or camera—should be used to capture a new file for upload with file
upload control in supporting scenarios. See the {{HTMLElement("input/file", "file")}} input type.
If present on a checkbox
type, it indicates that the checkbox is checked by default (when the page loads). It does not indicate whether this checkbox is currently checked: if the checkbox’s state is changed, this content attribute does not reflect the change. (Only the HTMLInputElement
’s checked
IDL attribute is updated.)
Note: Unlike other input controls, a checkboxes and radio buttons value are only included in the submitted data if they are currently checked
. If they are, the name and the value(s) of the checked controls are submitted.
For example, if a checkbox whose name
is fruit
has a value
of cherry
, and the checkbox is checked, the form data submitted will include fruit=cherry
. If the checkbox isn't active, it isn't listed in the form data at all. The default value
for checkboxes and radio buttons is on
.
Valid for text
and search
input types only, the dirname
attribute enables the submission of the directionality of the element. When included, the form control will submit with two name/value pairs: the first being the {{anch('name')}} and {{anch('value')}}, the second being the value of the dirname
as the name with the value of ltr
or rtl
being set by the browser.
<form action="page.html" method="post">
<label>Fruit: <input type="text" name="fruit" dirname="fruit.dir" value="cherry"></label>
<input type="submit"/>
</form>
<!-- page.html?fruit=cherry&fruit.dir=ltr -->
When the form above is submitted, the input cause both the name
/ value
pair of fruit=cherry
and the dirname
/ direction pair of fruit.dir=ltr
to be sent.
click
事件 将不会被分发 。 并且,禁用的控件的值在提交表单时也不会被提交。如果 type 属性为 hidden,此属性将被忽略。<input>
across page loads. Use the {{htmlattrxref("autocomplete","input")}} attribute to control this feature.A string specifying the {{HTMLElement("form")}} element with which the input is associated (that is, its form owner). This string's value, if present, must match the {{htmlattrxref("id")}} of a <form>
element in the same document. If this attribute isn't specified, the <input>
element is associated with the nearest containing form, if any.
The form
attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document.
Note: An input can only be associated with one form.
Valid for the image
and submit
input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information.
Valid for the image
and submit
input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information.
Valid for the image
and submit
input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information.
Valid for the image
and submit
input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information.
Valid for the image
and submit
input types only. See the {{HTMLElement("input/submit", "submit")}} input type for more information.
Global attribute valid for all elements, including all the input types, it defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking. The value is used as the value of the {{htmlelement('label')}}'s for
attribute to link the label with the form control. See the {{anch('the label element')}} below.
Global value valid for all elements, it provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents. Values include none
text
, tel
, url
, email
, numeric
, decimal
, and search
.
The values of the list attribute is the {{domxref("Element.id", "id")}} of a {{HTMLElement("datalist")}} element located in the same document. The <datalist>
provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the {{htmlattrxref("type", "input")}} are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.
<datalist id="colorsxx"> <option>#ff0000</option> <option>#ee0000</option> <option>#dd0000</option> <option>#cc0000</option> <option>#bb0000</option> </datalist> <datalist id="numbersxx"> <option>0</option> <option>2</option> <option>4</option> <option>8</option> <option>16</option> <option>32</option> <option>64</option> </datalist> <datalist id="fruitsxx"> <option>cherry</option> <option>banana</option> <option>mango</option> <option>orange</option> <option>blueberry</option> </datalist> <datalist id="urlsxx"> <option>https://developer.mozilla.org</option> <option>https://caniuse.com/</option> <option>https://mozilla.com</option> <option>https://mdn.github.io</option> <option>https://www.youtube.com/user/firefoxchannel</option> </datalist> <p><label for="textx">Text</label> <input type="text" list="fruitsxx" id="textx"/></p> <p><label for="colorx">Color</label> <input type="color" list="colorsxx" id="colorx"/></p> <p><label for="rangex">Range</label> <input type="range" min="0" max="64" list="numbersxx" id="rangex"/></p> <p><label for="numberx">Number</label> <input type="number" min="0" max="64" list="numbersxx" id="numberx"/></p> <p><label for="urlx">URL</label> <input type="url" list="urlsxx" id="urlx"/></p>
{{EmbedLiveSample("datalist",400,275,"","", "nobutton")}}
It is valid on text
, search
, url
, tel
, email
, date
, month
, week
, time
, datetime-local
, number
, range
, and color
.
Per the specifications, the list
attribute is not supported by the hidden
, password
, checkbox
, radio
, file
, or any of the button types.
Depending on the browser, the user may see a custom color palette suggested, tic marks along a range, or even a input that opens like a select but allows for non-listed values. Check out the browser compatibility table for the other input types.
See the {{htmlelement('datalist')}} element.
Valid for text
, search
, url
, tel
, email
, and password
, it defines the minimum number of characters (as UTF-16 code units) the user can enter into the entry field. This must be an non-negative integer value smaller than or equal to the value specified by maxlength
. If no minlength
is specified, or an invalid value is specified, the input has no minimum length.
The input will fail constraint validation if the length of the text entered into the field is fewer than minlength
UTF-16 code units long, preventing form submission. See {{anch("Client-side validation")}} for more information.
placeholder
属性替换 {{ HTMLElement("label") }} 元素。他们的作用不同: {{ HTMLElement("label") }} 属性描述表单元素的角色; 也就是说,它展示预期的信息,而placeholder
属性是提示用户内容的输入格式。某些情况下 placeholder
属性对用户不可见, 所以当没有它时也需要保证 form 能被理解。{{ HTMLVersionInline(5) }} 如果控件的 type 属性为hidden, range, color, checkbox, radio, file 或 type 时,此属性会被忽略。
true
表示元素需要检查其拼写和语法。值default
表示该元素将根据默认行为进行操作,可能基于父元素自己的spellcheck
值。值false
表示不应该检查元素Global attribute valid for all elements, including all input types, containing a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip. The title should NOT be used as the primary explanation of the purpose of the form control. Instead, use the {{htmlelement('label')}} element with a for
attribute set to the form control's {{htmlattrdef('id')}} attribute. See {{anch("Labels")}} below.
radio
或checkbox
。注意,当重新加载页面时,如果在重新加载之前更改了值,Gecko 和 IE 将忽略 HTML 源代码中指定的值。<input>
属性<input>
. Possible attribute values are:
on
: Enable autocorrection.off
: Disable autocorrection.autocorrect
documentation in the Safari HTML Reference.go
, done
, next
, search
, and send
; these automatically get mapped to the appropriate string (and are case-insensitive).none
: Completely disables automatic capitalizationsentences
: Automatically capitalize the first letter of sentences.words
: Automatically capitalize the first letter of words.characters
: Automatically capitalize all characters.on
: {{deprecated_inline()}} Deprecated since iOS 5.off
: {{deprecated_inline()}} Deprecated since iOS 5.autocapitalize
documentation in the Safari HTML Referencesearch
. If the attribute is present, regardless of what its value is, the <input>
fires search
events as the user edits the text value. The event is only fired after an implementation-defined timeout has elapsed since the most recent keystroke, and new keystrokes reset the timeout. In other words, the event firing is debounced. If the attribute is absent, the search
event is only fired when the user explicitly initiates a search (e.g. by pressing the Enter key while within field). incremental
documentation in the Safari HTML Referencego
, done
, next
, search
, and send
. These automatically get mapped to the appropriate string and are case-insensitive.search
. It is used to control the maximum number of entries that should be displayed in the <input>
's native dropdown list of past search queries. Its value should be a nonnegative decimal integer.file
has to allow for the selection of directories only.The following methods are provided by the HTMLInputElement
interface which represents <input>
elements in the DOM. Also available are those methods specified by the parent interfaces, HTMLElement
, Element
, Node
, and EventTarget
.
checkValidity()
invalid
event at the element if the value isn't valid.reportValidity()
true
if the element's value passes validity checks; otherwise, returns false
.select()
<input>
element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing.setCustomValidity()
setRangeText()
selectMode
parameter is available to allow controlling how the existing content is affected.setSelectionRange()
stepDown()
stepUp()
Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specification target form controls based on their UI features, also known as UI pseudo-classes. The input element can also be targeted by type with attribute selectors. There are some properties that are especially useful as well.
Pseudo-class | Description |
---|---|
:enabled |
Any currently enabled element that can be activated (selected, clicked on, typed into, etc.) or accept focus and also has a disabled state, in which it can't be activated or accept focus. |
:disabled |
Any currently disabled element that has an enabled state, meaing it otherwise could be activated (selected, clicked on, typed into, etc.) or accept focus were it not disabled. |
:read-only |
Element not editable by the user |
:read-write |
Element that is editable by the user. |
:placeholder-shown |
Element that is currently displaying placeholder text, including input elements with the placeholder attribute present that has, as of yet, no value. |
:default |
Form elements that are the default in a group of related elements. Matches checkbox and radio input types that were checked on page load or render. |
:checked |
Matches checkbox and radio input types that are currently checked (and the (<option> in a <select> that is currently selected). |
:indeterminate |
checkbox elements whose indeterminate property is set to true by JavaScript, radio elements, when all radio buttons with the same name value in the form are unchecked, and <progress> elements in an indeterminate state |
:valid |
Form controls that can have constraint validation applied and are currently valid. |
:invalid |
Form controls that have constraint validation applied and are currently not valid. Matches a form control whose value doesn't match the constraints set on it by it's attributes, such as required, pattern , step and max. |
:in-range |
A non-empty input whose current value is within the range limits specified by the min and max attributes and the step . |
:out-of-range |
A non-empty input whose current value is NOT within the range limits specified by the min and max attributes or does not adher to the step constraint. |
:placeholder-shown |
An <input> or <textarea> element that is currently displaying placeholder text. |
:required |
<input> , <select> , or <textarea> element that has the required attribute set on it. Only matches elements that can be required. The attribute included on a non-requirable element will not make for a match. |
:optional |
<input> , <select> , or <textarea> element that does NOT have the required attribute set on it. Does not match elements that can't be required. |
:blank |
<input> and <textarea> elements that currently have no value. |
:user-invalid |
Similar to :invalid , but is activated on blur. Matches invalid input but only after the user interaction, such as by focusing on the control, leaving the control, or attempting to submit the form containing the invalid control. |
We can style a checkbox label based on whether the checkbox is checked or not. In this example, we are styling the color
and font-weight
of the <label>
that comes immediately after a checked input. We haven't applied any styles if the input
is not checked.
input:checked + label { color: red; font-weight: bold; }
It is possible to target different types of form controls based on their type using attribute selectors. CSS attribute selectors match elements based on either just the presence of a attribute or the value of a given attribute.
/* matches a password input */ input[type="password"] {} /* matches a form control whose valid values are limited to a range of values*/ input[min][max] {} /* matches a form control with with a pattern attribute */ input[pattern] {}
By default, the appearance of placeholder text is a translucent or light gray. The ::placeholder
pseudo-element is the input's placeholder text. It can be styled with a limited subset of CSS properties.
::placeholder { color: blue; }
Only the subset of CSS properties that apply to the ::first-line
pseudo-element can be used in a rule using ::placeholder
in its selector.
appearance
The appearance
property enables the displaying of (almost) any element as a platform-native style based on the operating system's theme as well as the removal of any platform-native styling with the none
value.
You could make a <div>
look like a radio button with div {appearance: radio;}
or a radio look like a checkbox with [type="checkbox] {appearance: checkbox;}
, but don't.
Setting appearance: none
removes platform native borders, but not functionality.
caret-color
A property specific to text entry-related elements is the CSS caret-color
property, which lets you set the color used to draw the text input caret:
<label for="textInput">Note the red caret:</label> <input id="textInput" class="custom" size="32">
input.custom { caret-color: red; font: 16px "Helvetica", "Arial", "sans-serif" }
object-position
and object-fit
In certain cases (typically involving non-textual inputs and specialized interfaces), the <input>
element is a replaced element. When it is, the position and size of the element's size and positioning within its frame can be adjusted using the CSS object-position
and object-fit
properties
For more information about adding color to elements in HTML, see:
Also see:
Labels are needed to associate assistive text with an <input>
. The <label>
element provides explanatory information about a form field that is always appropriate (aside from any layout concerns you have). It's never a bad idea to use a <label>
to explain what should be entered into an <input>
or <textarea>
.
The semantic pairing of <input>
and <label>
elements is useful for assistive technologies such as screen readers. By pairing them using the <label>
's for
attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.
It does not suffice to have plain text adjacent to the <input>
element,. Rather, usability and accessibility requires the inclusion of either implicit or explicit <label>
:
<!-- inaccessible --> <p>Enter your name: <input id="name" type="text" size="30"></p> <!-- implicit label --> <p><label>Enter your name: <input id="name" type="text" size="30"></label></p> <!-- explicit label --> <p><label for="name">Enter your name: </label><input id="name" type="text" size="30"></p>
The first example is inaccessible: no relationship exists between the prompt and the <input>
element.
In addition to an accessible name, the label provides a larger 'hit' area for mouse and touch screen users to click on or touch. By pairing a <label>
with an <input>
, clicking on either one will focus the <input>
. If you use plain text to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.
As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your web site—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.
The placeholder
attribute lets you specify a text that appears within the <input>
element's content area itself when empty. The placeholder should never be required in order to understand your forms. It is not a label, and should not be used as a substitute, because it isn't. The placeholder is used to show an example input, not an explanation or prompt. Not only is the placeholder not accessible to screen readers, but once the user enters any text into the form control, or if the form control already has a value, there is no placeholder. Browsers with automatic page translation features may skip over attributes when translating, meaning the placeholder
may not get translated.
Don't use the placeholder
attribute if you can avoid it. If you need to label an <input>
element, use the <label>
element
In addition to using CSS to style inputs based on the :valid
or :invalid
UI states based on the current state of each input, as noted in the UI pseudo-classes section above, the browser provides for client-side validation on (attempted) form submission. On form submission, if their is a form control that fails constraint validation, supporting browsers will display an error message on the first invalid form control; displaying a default message based on the error type, or a message set by you.
Some input types and other attributes place limits on what values are valid for a given input. For example, <input type="number" min="2" max="10" step="2">
means only the number 2, 4, 6, 8, or 10 are valid. Several errors could occur, including a rangeUnderflow
error if the value is less than 2, rangeOverflow
if greater than 10, stepMismatch
if the value is a number between 2 and 10, but not an even integer (does not match the requirements of the step
attribute), or typeMismatch
if the value is not a number.
Specific attributes and their values can lead to specific error ValidityState
Attribute | Relevent property | Description |
---|---|---|
max | validityState.rangeOverflow |
Occurs when the value is greater than the maximum value as defined by the max attribute |
maxlength | validityState.tooLong |
Occurs when the number of characters is greater than the number allowed by the maxlength property |
min | validityState.rangeUnderflow |
Occurs when the value is less than the minimum value as defined by the min attribute |
minlength | validityState.tooShort |
Occurs when the number of characters is less than the number required by the minlength property |
pattern | validityState.patternMismatch |
Occurs when a pattern attribute is included with a valid regular expression and the value does not match it. |
required | validityState.valueMissing |
Occurs when the required attribute is present but the value is null or radio or checkbox is not checked. |
step | validityState.stepMismatch |
The value doesn't match the step increment. Increment default is 1 , so only integers are valid on type="number" is step is not included. step="any" will never throw this error. |
type | validityState.typeMismatch |
Occurs when the value is not of the correct type, for example a email does not contain an @ or a url doesn't contain a protocol. |
If a form control doesn't have the required attribute, no value, or an empty string, is not invalid. Even if the above attributes are present, with the exception of 'required'
, and empty string will not lead to an error.
We can set limits on what values we accept, and supporting browsers will natively validate these form values and alert the user if there is a mistake when the form is submitted.
In addition to the errors described in the table above, the validityState
interface contains the badInput
, valid
, and customError
boolean readonly properties. The validity object includes:
validityState.valueMissing
validityState.typeMismatch
validityState.patternMismatch
validityState.tooLong
validityState.tooShort
validityState.rangeUnderflow
validityState.rangeOverflow
validityState.stepMismatch
validityState.badInput
validityState.valid
validityState.customError
For each of these Boolean properties, a value of true
indicates that the specified reason validation may have failed is true, with the exception of the valid
property, which is true
if the element's value obeys all constraints.
If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or null
), the form will be be prevented from being submitted. If there is no custom error message, and none of the other properties return true, valid
will be true, and the form can be submitted.
function validate(input) { let validityState_object = input.validity; if(validityState_object.valueMissing) { input.setCustomValidity('A value is required'); } else if (input.rangeUnderflow) { input.setCustomValidity('Your value is too low'); } else if (input.rangeOverflow) { input.setCustomValidity('Your value is too high'); } else { input.setCustomValidity(''); } }
The last line, setting the custom validity message to the error string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all of the values are valid, until the message is null
.
If you want to present a custom error message when a field fails to validate, you need to use the Constraint validation features available on <input>
(and related) elements. Take the following form:
<form> <label for="name">Enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[A-Za-z]+"> <button>Submit</button> </form>
The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern
.
If you wanted to instead display custom error messages, you could use JavaScript like the following:
const nameInput = document.querySelector('input'); const form = document.querySelector('form'); nameInput.addEventListener('input', () => { nameInput.setCustomValidity(''); nameInput.checkValidity(); }); nameInput.addEventListener('invalid', () => { if(nameInput.value === '') { nameInput.setCustomValidity('Enter your username!'); } else { nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!'); } });
The example renders like so:
In brief:
checkValidity()
method via the input
event handler.invalid
event is raised, and the invalid
event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn't match the pattern, using an if()
block, and set a custom validity error message.setCustomValidity()
with an empty string value. We therefore do this every time the input
event is raised. If you don't do this, and a custom validity was previously set, the input will register as invalid, even if it current contains a valid value on submission.Note: Always validate input constraints both client side and server side. Constraint validation doesn't remove the need for validation on the server side. Invalid values can still be sent by older browsers or by bad actors.
Note: Firefox supported a proprietary error attribute — x-moz-errormessage
— for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see bug 1513890).
The allowed inputs for certain <input>
types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.
Firefox uses the following heuristics to determine the locale to validate the user's input (at least for type="number"
):
lang
/xml:lang
attribute on the element or any of its parents.Content-Language
HTTP header. Or,Content categories | Flow content, listed, submittable, resettable, form-associated element, phrasing content. If the type is not hidden , then labelable element, palpable content. |
---|---|
Permitted content | None, it is an empty element. |
Tag omission | Must have a start tag and must not have an end tag. |
Permitted parents | Any element that accepts phrasing content. |
Permitted ARIA roles |
|
DOM interface | HTMLInputElement |
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of '<input>' in that specification. |
Living Standard | |
HTML Media Capture The definition of 'capture attribute' in that specification. |
Recommendation | Adds the capture attribute |
HTML5 The definition of '<input>' in that specification. |
Recommendation | |
HTML 4.01 Specification The definition of '<form>' in that specification. |
Recommendation |
When including inputs, it is an accessibilty requirement to add labels along side. This is needed so those who use assistive technologies can tell what the input is for. Also, clicking or touching a label gives focus to the label's associated form control. This improves the accessibility and usability for sighted users, increases the area a user can click or touch to activate the form control. this is especially useful (and even needed) for radio buttons and checkboxes, which are tiny. For more information about labels in general see Labels .
The following is an example of how to associate the <label>
with an <input>
element in the above style. You need to give the <input>
an id
attribute. The <label>
then needs a for
attribute whose value is the same as the input's id
.
<label for="peas">Do you like peas?</label> <input type="checkbox" name="peas" id="peas">
Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44 CSS pixels is recommended.
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
input |
Chrome Full support Yes | Edge Full support 12 | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support 1 | Samsung Internet Android Full support Yes |
type="button" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support 1 | WebView Android Full support Yes | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 |
type="checkbox" |
Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="color" |
Chrome Full support 20 | Edge Full support 14 | Firefox Full support 29
|
IE No support No | Opera Full support 12 | Safari Full support 12.1 | WebView Android Full support 4.4 | Chrome Android Full support 25 | Firefox Android Full support 27 | Opera Android Full support 12 | Safari iOS Full support 12.2 | Samsung Internet Android Full support 1.5 |
type="date" |
Chrome Full support 20 | Edge Full support 12 | Firefox Full support 57 | IE No support No | Opera Full support 11 | Safari No support No
|
WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 57 | Opera Android Full support 11 | Safari iOS Full support 5 | Samsung Internet Android Full support Yes |
type="datetime-local" |
Chrome Full support 20 | Edge Full support 12 | Firefox No support No
|
IE No support No | Opera Full support 11 | Safari No support No
|
WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support 11 | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="email" |
Chrome Full support 5 | Edge Full support 12 | Firefox Full support Yes | IE Full support 10 | Opera Full support 11 | Safari Full support Yes | WebView Android ? | Chrome Android ? | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support 3.1
|
Samsung Internet Android ? |
type="file" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1
|
IE Full support Yes | Opera Full support 11 | Safari Full support 1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support 11 | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="hidden" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support Yes | Opera Full support 2 | Safari Full support 1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="image" |
Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android ? | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android ? |
x-moz-errormessage attribute
|
Chrome No support No | Edge No support No | Firefox No support ? — 66 | IE No support No | Opera No support No | Safari No support No | WebView Android No support No | Chrome Android No support No | Firefox Android No support ? — 66 | Opera Android No support No | Safari iOS No support No | Samsung Internet Android No support No |
type="month" |
Chrome Full support 20 | Edge Full support 12 | Firefox No support No
|
IE No support No | Opera Full support 11 | Safari No support No
|
WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android No support No | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="number" |
Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support 10 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="password" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 2 | Opera Full support 2 | Safari Full support 1 | WebView Android ? | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="radio" |
Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="range" |
Chrome Full support 4 | Edge Full support 12 | Firefox Full support 23 | IE Full support 10 | Opera Full support 11 | Safari Full support 3.1 | WebView Android Full support 4.4
|
Chrome Android Full support 57 | Firefox Android Full support 52 | Opera Android Full support Yes | Safari iOS Full support 5.1 | Samsung Internet Android Full support 7.0 |
type="reset" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1
|
IE Full support Yes | Opera Full support Yes | Safari Full support 1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4
|
Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="search" |
Chrome Full support 5 | Edge Full support 12 | Firefox Full support 4 | IE Full support 10 | Opera Full support 10.6 | Safari Full support 5 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="submit" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1
|
IE Full support Yes | Opera Full support Yes | Safari Full support 1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4
|
Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="tel" |
Chrome Full support Yes | Edge Full support 12 | Firefox Full support Yes | IE Full support 10 | Opera Full support 11 | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="text" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support 1 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="time" |
Chrome Full support 20 | Edge Full support 12 | Firefox Full support 57 | IE No support No | Opera Full support 10 | Safari No support No
|
WebView Android Full support Yes | Chrome Android Full support 25 | Firefox Android Full support 57 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.5 |
type="url" |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support Yes | IE Full support 10 | Opera Full support 11 | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
type="week" |
Chrome Full support 20 | Edge Full support 12 | Firefox No support No
|
IE No support No | Opera Full support 11 | Safari No support No
|
WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes |
<input>
element is a replaced element. When it is, the position and size of the elemnt's size and positioning within its frame can be adjusted using the CSS {{cssxref("object-position")}} and {{cssxref("object-fit")}} properties