HTML Input Types
This chapter describes the different types for the HTML <input> element.
HTML Input Types
Here are the different input types you can use in HTML:
- <input type="button">
- <input type="checkbox">
- <input type="color">
- <input type="date">
- <input type="datetime-local">
- <input type="email">
- <input type="file">
- <input type="hidden">
- <input type="image">
- <input type="month">
- <input type="number">
- <input type="password">
- <input type="radio">
- <input type="range">
- <input type="reset">
- <input type="search">
- <input type="submit">
- <input type="tel">
- <input type="text">
- <input type="time">
- <input type="url">
- <input type="week">
Tip: The default value of the type attribute is "text".
Input Type Text
<input type="text"> defines a single-line text input field:
Example
This is how the HTML code above will be displayed in a browser:
Input Type Password
<input type="password"> defines a password field:
Example
This is how the HTML code above will be displayed in a browser:
The characters in a password field are masked (shown as asterisks or circles).
Input Type Submit
<input type=»submit»> defines a button for submitting form data to a form-handler.
The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form’s action attribute:
Example
This is how the HTML code above will be displayed in a browser:
If you omit the submit button’s value attribute, the button will get a default text:
Example
Input Type Reset
<input type=»reset»> defines a reset button that will reset all form values to their default values:
Example
This is how the HTML code above will be displayed in a browser:
If you change the input values and then click the «Reset» button, the form-data will be reset to the default values.
Input Type Radio
<input type="radio"> defines a radio button.
Radio buttons let a user select ONLY ONE of a limited number of choices:
Example
<p>Choose your favorite Web language:</p>
This is how the HTML code above will be displayed in a browser:
HTML
CSS
JavaScript
Input Type Checkbox
<input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number of choices.
Example
This is how the HTML code above will be displayed in a browser:
I have a bike
I have a car
I have a boat
Input Type Button
<input type="button"> defines a button:
Example
This is how the HTML code above will be displayed in a browser:
Input Type Color
The <input type="color"> is used for input fields that should contain a color.
Depending on browser support, a color picker can show up in the input field.
Example
Input Type Date
The <input type="date"> is used for input fields that should contain a date.
Depending on browser support, a date picker can show up in the input field.
Example
You can also use the min and max attributes to add restrictions to dates:
Example
Input Type Datetime-local
The <input type="datetime-local"> specifies a date and time input field, with no time zone.
Depending on browser support, a date picker can show up in the input field.
Example
Input Type Email
The <input type="email"> is used for input fields that should contain an e-mail address.
Depending on browser support, the e-mail address can be automatically validated when submitted.
Some smartphones recognize the email type, and add ".com" to the keyboard to match email input.
Example
Input Type Image
The <input type="image"> defines an image as a submit button.
The path to the image is specified in the src attribute.
Example
Input Type File
The <input type="file"> defines a file-select field and a "Browse" button for file uploads.
Example
Input Type Hidden
The <input type="hidden"> defines a hidden input field (not visible to a user).
A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted.
A hidden field often stores what database record that needs to be updated when the form is submitted.
Note: While the value is not displayed to the user in the page’s content, it is visible (and can be edited) using any browser’s developer tools or "View Source" functionality. Do not use hidden inputs as a form of security!
Example
Input Type Month
The <input type="month"> allows the user to select a month and year.
Depending on browser support, a date picker can show up in the input field.
Example
Input Type Number
The <input type="number"> defines a numeric input field.
You can also set restrictions on what numbers are accepted.
The following example displays a numeric input field, where you can enter a value from 1 to 5:
Example
Input Restrictions
Here is a list of some common input restrictions:
| Attribute | Description |
|---|---|
| checked | Specifies that an input field should be pre-selected when the page loads (for type="checkbox" or type="radio") |
| disabled | Specifies that an input field should be disabled |
| max | Specifies the maximum value for an input field |
| maxlength | Specifies the maximum number of character for an input field |
| min | Specifies the minimum value for an input field |
| pattern | Specifies a regular expression to check the input value against |
| readonly | Specifies that an input field is read only (cannot be changed) |
| required | Specifies that an input field is required (must be filled out) |
| size | Specifies the width (in characters) of an input field |
| step | Specifies the legal number intervals for an input field |
| value | Specifies the default value for an input field |
You will learn more about input restrictions in the next chapter.
The following example displays a numeric input field, where you can enter a value from 0 to 100, in steps of 10. The default value is 30:
Example
Input Type Range
The <input type="range"> defines a control for entering a number whose exact value is not important (like a slider control). Default range is 0 to 100. However, you can set restrictions on what numbers are accepted with the min , max , and step attributes:
Example
Input Type Search
The <input type="search"> is used for search fields (a search field behaves like a regular text field).
Example
Input Type Tel
The <input type="tel"> is used for input fields that should contain a telephone number.
Example
Input Type Time
The <input type="time"> allows the user to select a time (no time zone).
Depending on browser support, a time picker can show up in the input field.
Example
Input Type Url
The <input type="url"> is used for input fields that should contain a URL address.
Depending on browser support, the url field can be automatically validated when submitted.
Some smartphones recognize the url type, and adds ".com" to the keyboard to match url input.
Example
Input Type Week
The <input type="week"> allows the user to select a week and year.
Depending on browser support, a date picker can show up in the input field.
<input>¶
Тег <input> (от англ. input — ввод) является одним из разносторонних элементов формы и позволяет создавать разные части интерфейса и обеспечивать взаимодействие с пользователем.
Главным образом <input> предназначен для создания текстовых полей, различных кнопок, переключателей и флажков.
Основной атрибут <input> , определяющий вид элемента — type . Он позволяет задавать следующие элементы формы: текстовое поле ( text ), поле с паролем ( password ), переключатель ( radio ), флажок ( checkbox ), скрытое поле ( hidden ), кнопка ( button ), кнопка для отправки формы ( submit ), кнопка для очистки формы ( reset ), поле для отправки файла ( file ), кнопка с изображением ( image ) и др. Для каждого элемента существует свой список атрибутов, которые определяют его вид и характеристики. Кроме того, в HTML5 добавлено ещё более десятка новых атрибутов.
Синтаксис¶
Закрывающий тег не требуется.
Атрибуты¶
Также для этого элемента доступны универсальные атрибуты.
accept¶
Устанавливает фильтр на типы файлов, которые вы можете отправить через поле загрузки файлов. Тип файла указывается как MIME-тип, при нескольких значениях они перечисляются через запятую. Если файл не подходит под установленный фильтр, он не показывается в окне выбора файлов.
Применяется к полю для отправки файла ( <input type=»file»> ).
Поддержка браузерами
Can I Use input-file-accept? Data on support for the input-file-accept feature across the major browsers from caniuse.com.
Синтаксис
Значения
Имя MIME-типа в любом регистре, несколько значений перечисляются через запятую.
В HTML5 также допустимо в качестве значения указывать audio/* для выбора всех звуковых файлов, video/* для видеофайлов и image/* для всех графических файлов.
Значение по умолчанию
Атрибут alt устанавливает альтернативный текст для поля с изображением. Такой текст позволяет получить текстовую информацию о рисунке при отключенной в браузере загрузке изображений, а также предназначен для поисковых систем.
Синтаксис
Значения
Любая подходящая текстовая строка.
Значение по умолчанию
autocomplete¶
Этот атрибут помогает заполнять поля форм текстом, который был введён в них ранее. Значения сохраняет и подставляет браузер, при этом автозаполнение по соображениям безопасности может отключаться пользователем в настройках браузера и не может в таком случае управляться атрибутом autocomplete .
При вводе первых букв текста выводится список сохранённых ранее значений, из которого можно выбрать необходимое.
Автозаполнение конкретного поля формы привязывается к его атрибуту name и при смене значения теряется.
Синтаксис
Значения
on Включает автозаполнение текста. off Отключает автозаполнение. Это значение обычно используется для отмены сохранения в браузере важных данных (паролей, номеров банковских карт), а также редко вводимых или уникальных данных (капча).
Значение по умолчанию
Зависит от настроек браузера.
autofocus¶
Автоматически устанавливает фокус в поле формы. В таком поле можно сразу набирать текст без явного щелчка по нему курсором мыши.
Синтаксис
Значения
Значение по умолчанию
По умолчанию атрибут autofocus не установлен.
checked¶
Этот атрибут определяет, помечен ли заранее такой элемент формы, как флажок или переключатель. В случае использования переключателей ( radiobutton ) может быть отмечен только один элемент группы, для флажков ( checkbox ) допустимо пометить хоть все элементы.
Синтаксис
Значения
Значение по умолчанию
По умолчанию этот атрибут выключен.
dirname¶
При наличии атрибута dirname на сервер отправляется пара имя/значение, где имя задаётся атрибутом dirname , а значение подставляется браузером. Для текста, идущего слева направо, значение будет ltr , а для текста справа налево (иврита, к примеру) значение будет rtl .
Синтаксис
Значения
Произвольная текстовая строка, которая служит именем параметра. Чтобы показать, что этот параметр указывает направление текста, обычно в конце строки добавляют .dir .
Значение по умолчанию
disabled¶
Блокирует доступ и изменение поля формы. Оно в таком случае отображается серым и недоступным для активации пользователем. Кроме того, такое поле не может получить фокус путем нажатия на клавишу Tab, мышью или другим способом. Тем не менее, такое состояние поля можно менять с помощью скриптов. Заблокированное в поле значение не передаётся на сервер.
Синтаксис
Значения
Значение по умолчанию
По умолчанию этот атрибут выключен.
Связывает поле с формой по её идентификатору. Такая связь необходима в случае, когда поле располагается за пределами <form> , например, при создании её программно или по соображениям дизайна.
Синтаксис
Значения
Идентификатор формы (значение атрибута id элемента <form> ).
Значение по умолчанию
formaction¶
Определяет адрес обработчика формы — это программа, которая получает данные формы и производит с ними желаемые действия. Атрибут formaction по своему действию аналогичен атрибуту action элемента <form> .
Синтаксис
Значения
formenctype¶
Устанавливает способ кодирования данных формы при их отправке на сервер. Обычно явно указывается в случае, когда используется поле для отправки файла ( input type=»file» ). Этот атрибут по своему действию аналогичен атрибуту enctype элемента <form> , при совместном использовании formenctype и enctype последний игнорируется.
Синтаксис
Значения
application/x-www-form-urlencoded Вместо пробелов ставится + , символы вроде русских букв кодируются их шестнадцатеричными значениями (например, %D0%9F%D0%B5%D1%82%D1%8F вместо Петя ). multipart/form-data Данные не кодируются. Это значение применяется при отправке файлов. text/plain Пробелы заменяются знаком + , буквы и другие символы не кодируются.
Значение по умолчанию
formmethod¶
Атрибут сообщает браузеру, каким методом следует передавать данные формы на сервер.
Синтаксис
Значения
Различают два метода — GET и POST , которые задаются ключевыми словами get и post .
get Этот метод предназначен для передачи данных формы непосредственно в адресной строке в виде пар « имя=значение », которые добавляются к адресу страницы после вопросительного знака и разделяются между собой амперсандом (символ & ). Полный адрес к примеру будет http://site.ru/doc/?name=Vasya&password=pup . Объём данных в методе ограничен 4 Кб. post Посылает на сервер данные в запросе браузера, объём пересылаемых данных ограничен лишь настройками сервера.
Значение по умолчанию
formnovalidate¶
Отменяет встроенную проверку данных введённых пользователем в форме на корректность перед отправкой формы. Такая проверка делается браузером автоматически для полей <input type=»email»> , <input type=»url»> , а также при наличии атрибута pattern или required у элемента <input> .
Синтаксис
Значения
Значение по умолчанию
По умолчанию этот атрибут выключен.
formtarget¶
Определяет имя фрейма, в которое будет загружаться результат, возвращаемый обработчиком формы в виде HTML-документа.
Синтаксис
Значения
В качестве значения используется имя фрейма, заданное атрибутом name . Если установлено несуществующее имя, то будет открыта новая вкладка. В качестве зарезервированных имен можно указывать следующие.
_blank Загружает страницу в новую вкладку браузера. _self Загружает страницу в текущую вкладку. _parent Загружает страницу во фрейм-родитель; если фреймов нет, то это значение работает как _self . _top Отменяет все фреймы и загружает страницу в полном окне браузера; если фреймов нет, то это значение работает как _self .
Значение по умолчанию
Указывает на список вариантов, созданный с помощью элемента <datalist> , которые можно выбирать при наборе текста. Изначально этот список скрыт и становится доступным при получении полем фокуса.
Синтаксис
Значения
Имя идентификатора элемента <datalist> .
Значение по умолчанию
Устанавливает верхнее значение для ввода числа или даты в поле формы.
Синтаксис
Значения
Целое положительное или отрицательное число (для type=»number» , type=»range» ).
Дата в формате ГГГГ-ММ-ДД (например: 2012-12-22) для type=»date» .
Значение по умолчанию
maxlength¶
Устанавливает максимальное число символов, которое может быть введено пользователем в текстовом поле. Когда это количество достигается при наборе, дальнейший ввод становится невозможным.
Синтаксис
Значения
Любое целое положительное число.
Значение по умолчанию
Ввод символов не ограничен.
Устанавливает нижнее значение для ввода числа или даты в поле формы.
Синтаксис
Значения
Целое положительное или отрицательное число (для type=»number» , type=»range» ).
Дата в формате ГГГГ-ММ-ДД (например: 2012-12-22) для type=»date» .
Значение по умолчанию
minlength¶
Задаёт минимальное число символов, которое может быть введено пользователем в текстовом поле. Если число символов меньше указанного значения, то браузер выдаёт сообщение об ошибке и не отправляет форму.
Синтаксис
Значения
Любое целое положительное число.
Значение по умолчанию
multiple¶
Атрибут multiple позволяет указывать одновременно несколько файлов в поле для загрузки файлов, а также несколько адресов электронной почты. При использовании двух и более почтовых адресов они должны перечисляться через запятую.
Синтаксис
Значения
Значение по умолчанию
По умолчанию атрибут multiple выключен.
Определяет уникальное имя элемента формы. Как правило, это имя используется при отправке данных на сервер или для доступа к введённым данным поля через скрипты.
Синтаксис
Значения
В качестве имени используется набор символов, включая числа и буквы. JavaScript чувствителен к регистру, поэтому при обращении к элементу по имени соблюдайте ту же форму написания, что и в атрибуте name .
Значение по умолчанию
pattern¶
Указывает регулярное выражение, согласно которому требуется вводить и проверять данные в поле формы. Если присутствует атрибут pattern , то форма не будет отправляться, пока поле не будет заполнено правильно.
Поддержка браузерами
Can I Use input-pattern? Data on support for the input-pattern feature across the major browsers from caniuse.com.
Синтаксис
Значения
Некоторые типовые регулярные выражения перечислены в табл. 1.
| Выражение | Описание |
|---|---|
| \d [0-9] | Одна цифра от 0 до 9. |
| \D [^0-9] | Любой символ кроме цифры. |
| \s | Пробел. |
| [A-Z] | Только заглавная латинская буква. |
| [A-Za-z] | Только латинская буква в любом регистре. |
| [А-Яа-яЁё] | Только русская буква в любом регистре. |
| [A-Za-zА-Яа-яЁё] | Любая буква русского и латинского алфавита. |
| [0-9] | Три цифры. |
| [A-Za-z] | Не менее шести латинских букв. |
| [0-9] | Не более трёх цифр. |
| [0-9] | От пяти до десяти цифр. |
| ^[a-zA-Z]+$ | Любое слово на латинице. |
| ^[А-Яа-яЁё\s]+$ | Любое слово на русском включая пробелы. |
| ^[ 0-9]+$ | Любое число. |
| [0-9] | Почтовый индекс. |
| \d+(,\d<2>)? | Число в формате 1,34 (разделитель запятая). |
| \d+(\.\d<2>)? | Число в формате 2.10 (разделитель точка). |
| \d<1,3>\.\d<1,3>\.\d<1,3>\.\d | IP-адрес |
placeholder¶
Выводит текст внутри поля формы, который исчезает при получении фокуса или при наборе текста. Обычно отображается серым цветом.
Поддержка браузерами
Can I Use input-placeholder? Data on support for the input-placeholder feature across the major browsers from caniuse.com.
Синтаксис
Значения
Текстовая строка. Если внутри строки предполагается пробел, её необходимо брать в двойные или одинарные кавычки.
Значение по умолчанию
readonly¶
Когда к элементу <input> добавляется атрибут readonly , текстовое поле не может изменяться пользователем, в том числе вводиться новый текст или модифицироваться существующий. Тем не менее, состояние и содержимое поля можно менять с помощью скриптов и данные отправляются на сервер.
Синтаксис
Значения
Значение по умолчанию
По умолчанию этот атрибут выключен.
required¶
Устанавливает поле формы обязательным для заполнения перед отправкой формы на сервер. Если обязательное поле пустое, браузер выведет сообщение об ошибке, а форма отправлена не будет. Вид и содержание сообщения зависит от браузера и меняться пользователем не может.
Синтаксис
Значения
Значение по умолчанию
По умолчанию атрибут required выключен.
Ширина текстового поля, которое определяется числом символов моноширинного шрифта. Иными словами, ширина задаётся количеством близстоящих букв одинаковой ширины по горизонтали. Если размер шрифта изменяется с помощью стилей, ширина также соответственно меняется.
Синтаксис
Значения
Любое целое положительное число.
Значение по умолчанию
Адрес графического файла, который будет отображаться на веб-странице в поле с изображением. Наиболее популярны файлы в формате PNG и JPEG.
Синтаксис
Значения
В качестве значения принимается полный или относительный путь к файлу.
Значение по умолчанию
Устанавливает шаг изменения числа для ползунков и полей ввода чисел.
Синтаксис
Значения
Любое целое или дробное число.
Значение по умолчанию
Сообщает браузеру, к какому типу относится элемент формы.
Поддержка браузерами
email , tel , url :
Can I Use input-email-tel-url? Data on support for the input-email-tel-url feature across the major browsers from caniuse.com.
Can I Use input-color? Data on support for the input-color feature across the major browsers from caniuse.com.
Can I Use input-range? Data on support for the input-range feature across the major browsers from caniuse.com.
Can I Use input-number? Data on support for the input-number feature across the major browsers from caniuse.com.
Can I Use input-search? Data on support for the input-search feature across the major browsers from caniuse.com.
date , time , datetime :
Can I Use input-datetime? Data on support for the input-datetime feature across the major browsers from caniuse.com.
Синтаксис
Значения
button Кнопка. checkbox Флажки. Позволяют выбрать более одного варианта из предложенных. file Поле для ввода имени файла, который пересылается на сервер. hidden Скрытое поле. Оно никак не отображается на веб-странице. image Поле с изображением. При нажатии на рисунок данные формы отправляются на сервер. password Обычное текстовое поле, но отличается от него тем, что все символы показываются звездочками. Предназначено для того, чтобы никто не подглядел вводимый пароль. radio Переключатели. Используются, когда следует выбрать один вариант из нескольких предложенных. reset Кнопка для возвращения данных формы в первоначальное значение. submit Кнопка для отправки данных формы на сервер. text Текстовое поле. Предназначено для ввода символов с помощью клавиатуры.
В HTML5 добавлены новые значения:
color Виджет для выбора цвета. date Поле для выбора календарной даты. datetime Указание даты и времени. datetime-local Указание местной даты и времени. email Для адресов электронной почты. number Ввод чисел. range Ползунок для выбора чисел в указанном диапазоне. search Поле для поиска. tel Для телефонных номеров. time Для времени. url Для веб-адресов. month Выбор месяца. week Выбор недели.
Значение по умолчанию
value¶
Определяет значение элемента формы, которое будет отправлено на сервер или получено с помощью клиентских скриптов. На сервер отправляется пара « имя=значение », где имя задаётся атрибутом name элемента <input> , а значение — атрибутом value .
Тег <input> HTML поле для ввода, кнопка
![]()
![]()
![]()
![]()
![]()
Тег <input> в HTML определяет элемент формы. В зависимости от выбранного типа, элемент input может принимать вид поля для ввода текста, кнопки, переключателя, чек-бокса и т.д.
Атрибут type HTML элемента input указывает на его тип. Тип элемента определяет его вариант отображения и функционал. Типы тега input (например, input type=»text» — текстовое поле, input type=»submit» — кнопка отправки, input type=»radio» — переключатель, input type=»checkbox» — чек-бокс, input type=»hidden» — скрытое поле, input type=»password» — пароль и т.д.) подробно описаны ниже.
Тег поля ввода <input> , как и тег кнопки <button> , может быть использован как кнопка отправки HTML форм. Для этого input должен иметь тип submit, находиться внутри HTML кода формы <form> или быть привязанным к форме с помощью атрибута form .
Тег <input> HTML является элементом формы. Подробно о создании форм описано в статье: Все про формы и поля в HTML. Создание и работа с формами.
Синтаксис
Input type button — простая кнопка
Тип button соответствует простой кликабельной кнопке. Действия, которые будут происходить по нажатию кнопки, определяются через JavaScript.
HTML код input type=»button» :
Input type checkbox — чек-бокс, флажок, галочка
Тип checkbox представляет собой поле, которое пользователь может отметить (чек-бокс). У поля checkbox есть только 2 состояния — отмечен или не отмечен. При отправке формы на сервер, данные передаются только для отмеченных чек-боксов.
Если для чек-бокса не задан атрибут value , как значение будет использовано значение по умолчанию — «on». Часто чек-боксы используются вместе с тегом <label> , где указывается подпись чек-бокса.
Обычно чек-бокс отображается в виде квадрата, внутри которого находится галочка, если чек-бокс отмечен.
HTML код input type=»checkbox» :
Input type color — выбор цвета
Тип color представляет собой поле, в котором пользователь может выбрать цвет. Цвет задается в формате HEX.
HTML код input type=»color» :
Input type date — поле для ввода даты
Тип date представляет собой поле, в которое пользователь может ввести дату. Дата включает в себя год, месяц и число.
Стандартный формат даты YYYY-MM-DD, например, «2005-01-20» (соответствует 20 января 2005г.). Подробнее о дате в HTML.
Обычно, при заполнении поля, браузеры отображают возле него календарь, в котором можно выбрать дату. В этом случае формат даты для пользователя может быть изменен, но на сервер отправится дата в стандартном формате.
HTML код input type=»date» :
Input type datetime — дата и время
Тип datetime представляет собой поле, в которое пользователь может ввести дату и время с указанием временной зоны.
Этот тип поля устарел, использовать его не рекомендуется. Используйте <input type=»datetime-local»> вместо него.
Input type datetime-local — локальное время
Тип datetime-local представляет собой поле, в которое пользователь может ввести дату и время (без указания временной зоны).
Обычно, при заполнении поля, браузеры отображают возле него календарь, в котором можно выбрать значение.
Формат значения, отправляемого на сервер: YYYY-MM-DDThh:mm, например, «2007-08-11T13:18» (соответствует 11 августа 2007г, 13 часов, 18 минут).
HTML код input type=»datetime-local» :
Input type email — поле для ввода адреса электронной почты
Тип email представляет собой поле, в которое необходимо ввести адрес электронной почты. Браузеры контролируют правильность заполнения поля. Если введенное значение не соответствует формату email-адреса, браузер выведет сообщение об ошибке.
HTML код input type=»email» :
Input type file — поле для загрузки файла
Тип file представляет собой поле, в котором в качестве значения используются файлы.
При использовании в HTML форме поля <input> с типом file нужно установить значение multipart/form-data для атрибута enctype родительской формы.
HTML код input type=»file» :
Input type hidden — скрытое поле
Тип hidden представляет собой скрытое поле. Такое поле не будет показано пользователю (не отображается на странице сайта). Поля типа hidden используют для передачи служебной информации.
HTML код input type=»hidden» :
Input type image — кнопка-картинка
Тип image представляет собой картинку-кнопку. По нажатию на картинку (изображение) происходит отправка связанной формы. Адрес файла картинки определяется в атрибуте src .
HTML код input type=»image» :
Input type month — поле для ввода месяца
Тип month представляет собой поле, в которое пользователь может ввести месяц (месяц конкретного года).
Формат значения, отправляемого на сервер: YYYY-MM, например, «2001-11» (соответствует ноябрю 2001г.).
HTML код input type=»month» :
Input type number — поле для ввода чисел
Тип number представляет собой поле, в котором можно вводить только числа. Ограничение на вводимые числа можно задавать с помощью атрибутов max — максимальное значение, min — минимальное значение, step — шаг (подробнее в таблице атрибутов ниже).
HTML код input type=»number» :
Input type password — поле для ввода пароля
Тип password представляет собой поле, предназначенное для ввода пароля. Значение, введенное в такое поле, будет показано под маской (обычно в виде точек, количество которых отражает количество введенных символов).
HTML код input type=»password» :
Input type radio — переключатель
Тип radio представляет собой переключатель (также используется название радио кнопка).
Для создания переключателя используют несколько тегов input type=»radio» , имеющих одинаковые значения атрибута name . Таким образом создается группа, где каждый тег <input> соответствует одному положению переключателя. Одновременно выбранным может быть только один из элементов группы.
При отправке формы на сервер, данные передаются только у выбранного (отмеченного) тега радио-кнопки.
Для удобства использования, рядом с радио-кнопками обычно размещают подпись <label> .
HTML код переключателя из input type=»radio» :
Input type range — диапазон, ползунок HTML
Тип range представляет собой ползунок, с помощью которого можно выбрать значение в указанном диапазоне. Диапазон значений определяется с помощь атрибутов max — максимальное значение, min — минимальное значение. Атрибут step — устанавливает значение шага для ползунка.
HTML код input type=»range» :
Input type reset — кнопка сброса, очистки полей
Тип reset представляет собой кнопку, нажатие которой очищает заполнение полей в связанной форме. После нажатия кнопки reset поля будут возвращены к своему первоначальному состоянию.
HTML код input type=»reset» :
Input type search — поле для ввода поискового запроса
Тип search представляет собой поле, которое предназначено для ввода поискового запроса.
HTML код input type=»search» :
Input type submit — кнопка отправки формы
Тип submit соответствует кнопке отправки формы. По нажатию на кнопку типа submit будет вызвано событие отправки (submit) связанной HTML формы.
К одной HTML форме может быть привязано несколько кнопок отправки. На сервер будут переданы данные только той кнопки, которая вызвала событие submit.
HTML код input type=»submit» :
Input type tel — поле для ввода номера телефона
Тип tel представляет собой поле, которое предназначено для ввода номера телефона. По умолчанию шаблон ввода не установлен и поле может принимать любые текстовые значения. Указать шаблон можно с помощью атрибута pattern . Другой вариант — использование JavaScript библиотек для установки формата поля.
HTML код input type=»tel» :
Input type text — текстовое поле HTML
Тип text представляет собой текстовое поле для ввода. Текст в input с типом text вводится в одну строку.
Если нужно создать многострочное поле для ввода, используйте текстовую область <textarea> .
HTML код input type=»text» :
Input type time — поле для ввода времени
Тип time представляет собой поле, в котором пользователь может ввести время.
Стандартный формат: hh:mm, например, «14:45». Подробнее о времени в HTML.
HTML код input type=»time» :
Input type url — поле для ввода URL адреса
Тип url представляет собой поле, которое используется для ввода URL. Браузеры контролируют правильность заполнения поля. Если введенное значение не соответствует формату URL адреса, браузер выведет сообщение об ошибке.
HTML код input type=»url» :
Input type week — поле для выбора недели
Тип week представляет собой поле, в которое пользователь может ввести неделю (например, отметить с помощью календаря, который выводит браузер при вводе в поле).
Стандартный формат: YYYY-Wxx, где «хх» — номер недели, начиная от начала года. Например, «2011-W12» (соответствует 12-й неделе в 2011 году).
Обычно, при заполнении поля, браузеры отображают возле него календарь, в котором можно выбрать неделю. В этом случае формат значения для пользователя может быть изменен, но на сервер отправятся данные в стандартном формате.
HTML код input type=»week» :
Поддержка браузерами
| Тег | |||||
| <input> | Да | Да | Да | Да | Да |
Атрибуты тега input
audio/*
video/*
image/*
расширение файла
media_type
Определяет типы файлов, которые можно использовать в поле input.
Используется только для полей с типом file.
- audio/* — аудио файлы;
- video/* — видео файлы;
- image/* — файлы изображений;
- расширение файла — файлы, имеющие конкретные расширения (например, «.jpg», «.png»);
- media_type — файлы указанного медиа типа.
Альтернативный текст. Используется только для полей с типом image.
Содержит текст, который будет выведен в случае, если изображение невозможно отобразить, а также прочитан программой — скрин-ридером.
Атрибут указывает, должен ли браузер, при повторном использовании поля, подставлять в него значения, введенные пользователем во время предыдущего использования.
- on — автозаполнение включено (значение по умолчанию);
- off — автозаполнение выключено.
Если атрибут использован, значение атрибута autocomplete родительской формы <form> будет проигнорировано для данного поля.
Логический атрибут. Если указан, при загрузке документа фокус будет переведен на элемент ввода.
Логический атрибут. Используется только для полей с типами checkbox и radio.
Если указан, то чек-бокс (для checkbox) считается отмеченным или значение переключателя (для radio) выбранным.
Логический атрибут. Если указан, отключает возможность изменить состояние поля (ввести текст, поменять выбранное значение переключателя (для radio), отметить чек-бокс и т.п).
Данные поля, отмеченного этим атрибутом, не будут переданы на сервер при отправке формы.
Указывает на форму, к которой относится поле. Используется, если поле <input> находится вне HTML кода формы.
Если поле находится внутри тега <form>, то использовать атрибут form не нужно, поле по умолчанию привязано к форме, внутри которой находится.
URL адрес документа — обработчика формы. Используется для input с типом image и submit.
Если указан, форма будет отправлена по URL адресу, указанному в этом атрибуте, игнорируя атрибут action тега <form>.
Способ кодирования информации. Используется для input с типом image и submit.
Указывает как именно нужно кодировать информацию при отправке на сервер, вызванной нажатием кнопки, содержащей этот атрибут.
- application/x-www-form-urlencoded — все символы кодируются перед отправкой в шестнадцатеричные значения (HEX) ASCII, пробелы заменяются на «+». Значение по умолчанию;
- multipart/form-data — символы не кодируются. Значение обязательно нужно использовать в форме с полем input type=»file» (при использовании файлов в форме);
- text/plain — символы не кодируются, пробелы заменяются символом «+».
Атрибут используется только в случае отправки формы методом POST.
Этот атрибут переопределяет значение, указанное в атрибуте enctype тега <form>.
HTTP метод передачи данных родительской формы.
- GET — передача данных в URL с помощью пар имя-значение (name-value). Значение по умолчанию.
- POST — передача данных в теле HTTP запроса.
Используется только для input с типом image и submit.
Этот атрибут переопределяет значение, указанное в атрибуте method тега <form>.
Логический атрибут. Браузер не будет выполнять проверку правильности заполнения формы перед отправкой, вызванной нажатием input, содержащей этот атрибут. По умолчанию браузер проверяет наличие значения в обязательных полях (required), соответствие значений стандарту (например, для поля с типом email) и т.п.
Используется только для input с типом image и submit.
Этот атрибут переопределяет значение, указанное в атрибуте novalidate тега <form>.
Определяет где будет открыт результат обработки формы (ответ сервера), при отправке по нажатию кнопки с этим атрибутом:
- _blank — в новой вкладке или окне;
- _parent — в родительском окне;
- _self — в текущем окне (используется по умолчанию);
- _top — на весь экран.
Используется только для input с типом image и submit.
Этот атрибут переопределяет значение, указанное в атрибуте target тега <form>.
Высота изображения в пикселях.
Используется только для input с типом image.
Прикрепляет к полю список предопределенных вариантов <datalist>.
Максимальное значение для поля.
Необходимо указывать значение, соответствующее формату поля для которого используется атрибут.
Используется только для input с типом date, datetime, datetime-local, month, number, range, time и week.
Максимальное количество символов, допустимое для ввода в поле input.
Минимальное значение для поля.
Необходимо указывать значение, соответствующее формату поля для которого используется атрибут.
Используется только для input с типом date, datetime, datetime-local, month, number, range, time и week.
Логический атрибут. Если указан, позволяет указывать в поле более одного объекта.
Используется только для input с типом email и file.
При использовании с input type=»file» позволяет прикрепить несколько файлов.
При использовании с input type=»email» позволяет ввести несколько адресов email через запятую.
Имя поля. Используется при передаче данных формы на сервер. Значение поля (value) будет передано в переменной, имеющей имя, указанное в этом атрибуте.
Шаблон ввода. Содержит регулярное выражение, с которым будет сравниваться значение перед отправкой формы. Браузер будет блокировать отправку формы, пока значение в поле не будет удовлетворять указанному регулярному выражению.
Используется только для input с типом date, email, password, search, tel, text, url.
Текст, который будет отображаться внутри поля для ввода, когда оно не заполнено. Обычно это описание того, что должен ввести пользователь, либо пример заполнения.
Используется только для input с типом email, password, search, tel, text, url.
Логический атрибут. Если указан, пользователь не сможет изменить значение в поле. Используется для создания полей, доступных только для чтения.
Логический атрибут. Если указан, поле будет определено как обязательное для заполнения. Форма не будет отправлена на сервер, если такое поле не будет заполнено.
Заполнение контролируется браузером. При попытке отправить форму с незаполненным обязательным полем, браузеры обычно выводят на экран ошибку заполнения.
Используется только для input с типом checkbox, date,datetime, datetime-local, email, file, month, number, password, radio, search, tel, text, url, week.
Определяет ширину поля в символах. Ширина поля будет подобрана таким образом, чтобы в поле одновременно было видно количество символов, указанное в атрибуте.
Значение атрибута соответствует количеству символов только для моноширинных шрифтов.
Используется только для input с типом email, password, search, tel, text, url.
URL адрес файла изображения. Обязательный для заполнения.
Используется только для input с типом image.
Шаг изменения значения.
Значение по умолчанию: «1».
При указании числового значения в поле можно будет использовать только значения кратные указанному числу. Например, при указании «5» в поле можно будет ввести числа 0, 5, -5, 25, -155 и т.п., но нельзя будет ввести 1, -3, 28, 156 и т.п. (так как они не кратны числу «5»); при указании «2.5» в поле можно будет вводить 0, 2.5, 5, 7.5 и т.п., но нельзя будет 1, 2.4, 6.2, 8 и т.п. (так как они не кратны числу «2.5»).
При указании «any» поле будет принимать любые числа.
Используется только для input с типом date, datetime, datetime-local, month, number, range, time и week.
Тип элемента. Определяет отображение и функционал элемента.
Элементы одинакового типа могут отличаться в различных браузерах, однако, как правило, это не влияет на функциональность.
- button — простая кликабельная кнопка. Действие по нажатию кнопки определяется с помощью скриптов. Подробнее
- checkbox — чек-бокс (флажок, галочка). Подробнее
- color — окно выбора цвет. Подробнее
- date — поле для ввода даты. Подробнее
- datetime — поле для ввода даты и времени с указанием временной зоны. Этот тип поля является устаревшим. Подробнее
- datetime-local — поле для ввода локального времени (даты и времени). Подробнее
- email — поле для ввода адреса электронной почты. Подробнее
- file — поле, к которому можно прикрепить файлы в качестве значения. Подробнее
- hidden — скрытое поле. Подробнее
- image — кнопка-картинка, нажатие по которой вызывает событие отправки формы. Подробнее
- month — поле для ввода месяца и года (например, «декабрь, 2010г.»). Подробнее
- number — поле для ввода числа. Подробнее
- password — поле для ввода пароля. Подробнее
- radio — переключатель (одно из значений переключателя). Подробнее
- range — диапазон (ползунок). Подробнее
- reset — кнопка сброса введенных значений в форме. Подробнее
- search — поле для введения поискового запроса. Подробнее
- submit — кнопка, нажатие по которой вызывает событие отправки формы. Подробнее
- tel — поле для ввода телефона. Подробнее
- text — текстовое поле. Подробнее
- time — поле для ввода времени. Подробнее
- url — поле для ввода URL адресов. Подробнее
- week — поле для ввода недели (недели определенного года, например, «неделя 12, 2017г.»). Подробнее
Значение элемента, которое будет отправлено на сервер.
На сервер отправляется переменная, имеющая название, указанное в атрибуте name элемента и значение, указанное в этом атрибуте.
<input>: The Input (Form Input) element
The <input> HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. The <input> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes.
Try it
<input> types
How an <input> works varies considerably depending on the value of its type attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is text .
The available types are as follows:
Attributes
The <input> element is so powerful because of its attributes; the type attribute, described with examples above, being the most important. Since every <input> element, regardless of type, is based on the HTMLInputElement interface, they technically share the exact same set of attributes. However, in reality, most attributes have an effect on only a specific subset of input types. In addition, the way some attributes impact an input depends on the input type, impacting different input types in different ways.
This section provides a table listing all the attributes with a brief description. This table is followed by a list describing each attribute in greater detail, along with which input types they are associated with. Those that are common to most or all input types are defined in greater detail below. Attributes that are unique to particular input types—or attributes which are common to all input types but have special behaviors when used on a given input type—are instead documented on those types’ pages.
Attributes for the <input> element include the global HTML attributes and additionally:
| Attribute | Type or Types | Description |
|---|---|---|
| accept | file | Hint for expected file type in file upload controls |
| alt | image | alt attribute for the image type. Required for accessibility |
| autocomplete | all except checkbox , radio , and buttons | Hint for form autofill feature |
| capture | file | Media capture input method in file upload controls |
| checked | checkbox , radio | Whether the command or control is checked |
| dirname | search , text | Name of form field to use for sending the element’s directionality in form submission |
| disabled | all | Whether the form control is disabled |
| form | all | Associates the control with a form element |
| formaction | image , submit | URL to use for form submission |
| formenctype | image , submit | Form data set encoding type to use for form submission |
| formmethod | image , submit | HTTP method to use for form submission |
| formnovalidate | image , submit | Bypass form control validation for form submission |
| formtarget | image , submit | Browsing context for form submission |
| height | image | Same as height attribute for <img> ; vertical dimension |
| list | all except hidden , password , checkbox , radio , and buttons | Value of the id attribute of the <datalist> of autocomplete options |
| max | date , month , week , time , datetime-local , number , range | Maximum value |
| maxlength | text , search , url , tel , email , password | Maximum length (number of characters) of value |
| min | date , month , week , time , datetime-local , number , range | Minimum value |
| minlength | text , search , url , tel , email , password | Minimum length (number of characters) of value |
| multiple | email , file | Boolean. Whether to allow multiple values |
| name | all | Name of the form control. Submitted with the form as part of a name/value pair |
| pattern | text , search , url , tel , email , password | Pattern the value must match to be valid |
| placeholder | text , search , url , tel , email , password , number | Text that appears in the form control when it has no value set |
| popovertarget | button | Designates an <input type=»button»> as a control for a popover element |
| popovertargetaction | button | Specifies the action that a popover control should perform |
| readonly | all except hidden , range , color , checkbox , radio , and buttons | Boolean. The value is not editable |
| required | all except hidden , range , color , and buttons | Boolean. A value is required or must be check for the form to be submittable |
| size | text , search , url , tel , email , password | Size of the control |
| src | image | Same as src attribute for <img> ; address of image resource |
| step | date , month , week , time , datetime-local , number , range | Incremental values that are valid |
| type | all | Type of form control |
| value | all except image | The initial value of the control |
| width | image | Same as width attribute for <img> |
A few additional non-standard attributes are listed following the descriptions of the standard attributes.
Individual attributes
Valid for the file input type only, the accept attribute defines which file types are selectable in a file upload control. See the file input type.
Valid for the image button only, the alt attribute provides alternative text for the image, displaying the value of the attribute if the image src is missing or otherwise fails to load. See the image input type.
(Not a Boolean attribute!) The autocomplete attribute takes as its value a space-separated string that describes what, if any, type of autocomplete functionality the input should provide. A typical implementation of autocomplete recalls previous values entered in the same input field, but more complex forms of autocomplete can exist. For instance, a browser could integrate with a device’s contacts list to autocomplete email addresses in an email input field. See autocomplete for permitted values.
The autocomplete attribute is valid on hidden , text , search , url , tel , email , date , month , week , time , datetime-local , number , range , color , and password . This attribute has no effect on input types that do not return numeric or text data, being valid for all input types except checkbox , radio , file , or any of the button types.
See the autocomplete attribute for additional information, including information on password security and how autocomplete is slightly different for hidden than for other input types.
A Boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the <dialog> containing the element has been displayed).
Note: An element with the autofocus attribute may gain focus before the DOMContentLoaded event is fired.
No more than one element in the document may have the autofocus attribute. If put on more than one element, the first one with the attribute receives focus.
The autofocus attribute cannot be used on inputs of type hidden , since hidden inputs cannot be focused.
Warning: Automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. When autofocus is assigned, screen-readers «teleport» their user to the form control without warning them beforehand.
Use careful consideration for accessibility when applying the autofocus attribute. Automatically focusing on a control can cause the page to scroll on load. The focus can also cause dynamic keyboards to display on some touch devices. While a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content.
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 file input type.
Valid for both radio and checkbox types, checked is a Boolean attribute. If present on a radio type, it indicates that the radio button is the currently selected one in the group of same-named radio buttons. 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 name and value , the second being the value of the dirname as the name with the value of ltr or rtl being set by the browser.
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.
A Boolean attribute which, if present, indicates that the user should not be able to interact with the input. Disabled inputs are typically rendered with a dimmer color or using some other form of indication that the field is not available for use.
Specifically, disabled inputs do not receive the click event, and disabled inputs are not submitted with the form.
Note: Although not required by the specification, Firefox will by default persist the dynamic disabled state of an <input> across page loads. Use the autocomplete attribute to control this feature.
A string specifying the <form> element with which the input is associated (that is, its form owner). This string’s value, if present, must match the 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 submit input type for more information.
Valid for the image and submit input types only. See the submit input type for more information.
Valid for the image and submit input types only. See the submit input type for more information.
Valid for the image and submit input types only. See the submit input type for more information.
Valid for the image and submit input types only. See the submit input type for more information.
Valid for the image input button only, the height is the height of the image file to display to represent the graphical submit button. See the image input type.
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 <label> ‘s for attribute to link the label with the form control. See <label> .
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 value given to the list attribute should be the id of a <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 type 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.
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 an input that opens like a <select> but allows for non-listed values. Check out the browser compatibility table for the other input types.
Valid for date , month , week , time , datetime-local , number , and range , it defines the greatest value in the range of permitted values. If the value entered into the element exceeds this, the element fails constraint validation. If the value of the max attribute isn’t a number, then the element has no maximum value.
There is a special case: if the data type is periodic (such as for dates or times), the value of max may be lower than the value of min , which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM.
Valid for text , search , url , tel , email , and password , it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of minlength .
The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long. By default, browsers prevent users from entering more characters than allowed by the maxlength attribute. See Client-side validation for more information.
Valid for date , month , week , time , datetime-local , number , and range , it defines the most negative value in the range of permitted values. If the value entered into the element is less than this, the element fails constraint validation. If the value of the min attribute isn’t a number, then the element has no minimum value.
This value must be less than or equal to the value of the max attribute. If the min attribute is present but is not specified or is invalid, no min value is applied. If the min attribute is valid and a non-empty value is less than the minimum allowed by the min attribute, constraint validation will prevent form submission. See Client-side validation for more information.
There is a special case: if the data type is periodic (such as for dates or times), the value of max may be lower than the value of min , which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 PM to 4 AM.
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 a 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 Client-side validation for more information.
The Boolean multiple attribute, if set, means the user can enter comma separated email addresses in the email widget or can choose more than one file with the file input. See the email and file input type.
A string specifying a name for the input control. This name is submitted along with the control’s value when the form data is submitted.
Consider the name a required attribute (even though it’s not). If an input has no name specified, or name is empty, the input’s value is not submitted with the form! (Disabled controls, unchecked radio buttons, unchecked checkboxes, and reset buttons are also not sent.)
There are two special cases:
- _charset_ : If used as the name of an <input> element of type hidden, the input’s value is automatically set by the user agent to the character encoding being used to submit the form.
- isindex : For historical reasons, the name isindex is not allowed.
The name attribute creates a unique behavior for radio buttons.
Only one radio button in a same-named group of radio buttons can be checked at a time. Selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. The value of that one checked radio button is sent along with the name if the form is submitted,
When tabbing into a series of same-named group of radio buttons, if one is checked, that one will receive focus. If they aren’t grouped together in source order, if one of the group is checked, tabbing into the group starts when the first one in the group is encountered, skipping all those that aren’t checked. In other words, if one is checked, tabbing skips the unchecked radio buttons in the group. If none are checked, the radio button group receives focus when the first button in the same name group is reached.
Once one of the radio buttons in a group has focus, using the arrow keys will navigate through all the radio buttons of the same name, even if the radio buttons are not grouped together in the source order.
When an input element is given a name , that name becomes a property of the owning form element’s HTMLFormElement.elements property. If you have an input whose name is set to guest and another whose name is hat-size , the following code can be used:
When this code has run, guestName will be the HTMLInputElement for the guest field, and hatSize the object for the hat-size field.
Warning: Avoid giving form elements a name that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.
Valid for text , search , url , tel , email , and password , the pattern attribute defines a regular expression that the input’s value must match in order for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the ‘u’ flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.
If the pattern attribute is present but is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. If the pattern attribute is valid and a non-empty value does not match the pattern, constraint validation will prevent form submission.
Note: If using the pattern attribute, inform the user about the expected format by including explanatory text nearby. You can also include a title attribute to explain what the requirements are to match the pattern; most browsers will display this title as a tooltip. The visible explanation is required for accessibility. The tooltip is an enhancement.
See Client-side validation for more information.
Valid for text , search , url , tel , email , password , and number , the placeholder attribute provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that provides a hint as to the expected type of data, rather than an explanation or prompt. The text must not include carriage returns or line feeds. So for example if a field is expected to capture a user’s first name, and its label is «First Name», a suitable placeholder might be «e.g. Mustafa».
Note: The placeholder attribute is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels for more information.
Turns an <input type=»button»> element into a popover control button; takes the ID of the popover element to control as its value. See the Popover API landing page for more details.
Specifies the the action to be performed on a popover element being controlled by a control <input type=»button»> . Possible values are:
The button will hide a shown popover. If you try to hide an already hidden popover, no action will be taken.
The button will show a hidden popover. If you try to show an already showing popover, no action will be taken.
The button will toggle a popover between showing and hidden. If the popover is hidden, it will be shown; if the popover is showing, it will be hidden. If popovertargetaction is omitted, «toggle» is the default action that will be performed by the control button.
A Boolean attribute which, if present, indicates that the user should not be able to edit the value of the input. The readonly attribute is supported by the text , search , url , tel , email , date , month , week , time , datetime-local , number , and password input types.
See the HTML attribute: readonly for more information.
required is a Boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. The required attribute is supported by text , search , url , tel , email , date , month , week , time , datetime-local , number , password , checkbox , radio , and file inputs.
Valid for email , password , tel , url , and text , the size attribute specifies how much of the input is shown. Basically creates same result as setting CSS width property with a few specialities. The actual unit of the value depends on the input type. For password and text , it is a number of characters (or em units) with a default value of 20 , and for others, it is pixels (or px units). CSS width takes precedence over the size attribute.
Valid for the image input button only, the src is string specifying the URL of the image file to display to represent the graphical submit button. See the image input type.
Valid for date , month , week , time , datetime-local , number , and range , the step attribute is a number that specifies the granularity that the value must adhere to.
If not explicitly included:
- step defaults to 1 for number and range .
- Each date/time input type has a default step value appropriate for the type; see the individual input pages: date , datetime-local , month , time , and week .
The value must be a positive number—integer or float—or the special value any , which means no stepping is implied, and any value is allowed (barring other constraints, such as min and max ).
If any is not explicitly set, valid values for the number , date/time input types, and range input types are equal to the basis for stepping — the min value and increments of the step value, up to the max value, if specified.
For example, if you have <input type=»number» min=»10″ step=»2″> , then any even integer, 10 or greater, is valid. If omitted, <input type=»number»> , any integer is valid, but floats (like 4.2 ) are not valid, because step defaults to 1 . For 4.2 to be valid, step would have had to be set to any , 0.1, 0.2, or any the min value would have had to be a number ending in .2 , such as <input type=»number» min=»-5.2″>
Note: When the data entered by the user doesn’t adhere to the stepping configuration, the value is considered invalid in constraint validation and will match the :invalid pseudoclass.
See Client-side validation for more information.
Global attribute valid for all elements, including all the input types, an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation. As all input types except for input of type hidden are focusable, this attribute should not be used on form controls, because doing so would require the management of the focus order for all elements within the document with the risk of harming usability and accessibility if done incorrectly.
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 <label> element with a for attribute set to the form control’s id attribute. See Labels below.
A string specifying the type of control to render. For example, to create a checkbox, a value of checkbox is used. If omitted (or an unknown value is specified), the input type text is used, creating a plaintext input field.
Permitted values are listed in Input types above.
The input control’s value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using JavaScript to access the respective HTMLInputElement object’s value property. The value attribute is always optional, though should be considered mandatory for checkbox , radio , and hidden .
Valid for the image input button only, the width is the width of the image file to display to represent the graphical submit button. See the image input type.
Non-standard attributes
The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can’t be helped.
A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard.
Deprecated: use enterkeyhint instead.
(Safari only). A string which indicates how auto-capitalization should be applied while the user is editing this field. Permitted values are:
Do not automatically capitalize any text
Automatically capitalize the first character of each sentence.
Automatically capitalize the first character of each word.
Automatically capitalize every character.
(Safari only). A string which indicates whether to activate automatic correction while the user is editing this field. Permitted values are:
Enable automatic correction of typos, as well as processing of text substitutions if any are configured.
Disable automatic correction and text substitutions.
The Boolean attribute incremental is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the user agent to process the input as a live search. As the user edits the value of the field, the user agent sends search events to the HTMLInputElement object representing the search box. This allows your code to update the search results in real time as the user edits the search.
If incremental is not specified, the search event is only sent when the user explicitly initiates a search (such as by pressing the Enter or Return key while editing the field).
The search event is rate-limited so that it is not sent more frequently than an implementation-defined interval.
Similar to the -moz-orient non-standard CSS property impacting the <progress> and <meter> elements, the orient attribute defines the orientation of the range slider. Values include horizontal , meaning the range is rendered horizontally, and vertical , where the range is rendered vertically.
The results attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the <input> element’s natively-provided drop-down menu of previous search queries.
The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser’s default maximum number of entries is used.
The Boolean webkitdirectory attribute, if present, indicates that only directories should be available to be selected by the user in the file picker interface. See HTMLInputElement.webkitdirectory for additional details and examples.
Though originally implemented only for WebKit-based browsers, webkitdirectory is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative.
Methods
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 .
Returns true if the element’s value passes validity checks; otherwise, returns false and fires an invalid event at the element.
Returns true if the element’s value passes validity checks; otherwise, returns false , fires an invalid event at the element, and (if the event isn’t canceled) reports the problem to the user.
Selects the entire content of the <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.
Sets a custom message to display if the input element’s value isn’t valid.
Sets the contents of the specified range of characters in the input element to a given string. A selectMode parameter is available to allow controlling how the existing content is affected.
Selects the specified range of characters within a textual input element. Does nothing for inputs which aren’t presented as text input fields.
Decrements the value of a numeric input by one, by default, or by the specified number of units.
Increments the value of a numeric input by one or by the specified number of units.
Inputs, being replaced elements, have a few features not applicable to non form elements. There are CSS selectors that can specifically 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.
UI pseudo-classes
| 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, meaning 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> and <textarea> elements with the placeholder attribute present that has, as 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 its 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 adhere to the step constraint. |
| :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. |
Pseudo-classes example
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.
Attribute selectors
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 an attribute or the value of a given attribute.
::placeholder
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.
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
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:
Result
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
Styling
For more information about adding color to elements in HTML, see:
Additional features
Labels
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> .
Associated labels
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> :
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 website—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.
Placeholders are not accessible
The placeholder attribute lets you specify text that appears within the <input> element’s content area itself when it is empty. The placeholder should never be required 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 provide a hint as to what an inputted value should look like, 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, the placeholder disappears. Browsers with automatic page translation features may skip over attributes when translating, meaning the placeholder may not get translated.
Note: Don’t use the placeholder attribute if you can avoid it. If you need to label an <input> element, use the <label> element.
Client-side validation
Warning: Client-side validation is useful, but it does not guarantee that the server will receive valid data. If the data must be in a specific format, always verify it also on the server-side, and return a 400 HTTP response if the format is invalid.
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 there 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.
For the input types whose domain of possible values is periodic (that is, at the highest possible value, the values wrap back around to the beginning rather than ending), it’s possible for the values of the max and min properties to be reversed, which indicates that the range of permitted values starts at min , wraps around to the lowest possible value, then continues on until max is reached. This is particularly useful for dates and times, such as when you want to allow the range to be from 8 PM to 8 AM:
Specific attributes and their values can lead to a specific error ValidityState :
| Attribute | Relevant 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 an 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 , an 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:
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 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.
The last line, setting the custom validity message to the empty string is vital. If the user makes an error, and the validity is set, it will fail to submit, even if all the values are valid, until the message is null .
Custom validation error example
If you want to present a custom error message when a field fails to validate, you need to use the Constraint Validation API available on <input> (and related) elements. Take the following 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:
The example renders like so:
- We check the valid state of the input element every time its value is changed by running the checkValidity() method via the input event handler.
- If the value is invalid, an 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.
- As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.
- If it is valid, it will submit as you’d expect. For this to happen, the custom validity has to be cancelled, by invoking 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 currently 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 Firefox bug 1513890).
Localization
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» ):
- Try the language specified by a lang / xml:lang attribute on the element or any of its parents.
- Try the language specified by any Content-Language HTTP header. Or,
- If none specified, use the browser’s locale.
Technical summary
- type=button : button
- type=checkbox : checkbox
- type=email
- with no list attribute: textbox
- with list attribute: combobox
- with no list attribute: searchbox
- with list attribute: combobox
- with no list attribute: textbox
- with list attribute: combobox
- with no list attribute: textbox
- with list attribute: combobox
- with no list attribute: textbox
- with list attribute: combobox
- type=button : checkbox , combobox , link , menuitem , menuitemcheckbox , menuitemradio , option , radio , switch , tab
- type=checkbox : button when used with aria-pressed , menuitemcheckbox , option , switch
- type=image : link , menuitem , menuitemcheckbox , menuitemradio , radio , switch
- type=radio : menuitemradio
- type=text with no list attribute: combobox , searchbox , spinbutton
- type=color|date|datetime-local|email|file|hidden| month|number|password|range|reset|search|submit|tel|url|week or text with list attribute: no role permitted
Accessibility concerns
Labels
When including inputs, it is an accessibility requirement to add labels alongside. 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 .
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.