Атрибут type
Сообщает браузеру, к какому типу относится элемент формы.
Синтаксис
Значения
В табл. 1 перечислены возможные значения атрибута type и получаемый вид поля формы.
| Тип | Описание | Вид |
|---|---|---|
| button | Кнопка. | |
| checkbox | Флажки. Позволяют выбрать более одного варианта из предложенных. | Пиво Чай Кофе |
| file | Поле для ввода имени файла, который пересылается на сервер. | |
| hidden | Скрытое поле. Оно никак не отображается на веб-странице. | |
| image | Поле с изображением. При нажатии на рисунок данные формы отправляются на сервер. | |
| password | Обычное текстовое поле, но отличается от него тем, что все символы показываются звездочками. Предназначено для того, чтобы никто не подглядел вводимый пароль. | |
| radio | Переключатели. Используются, когда следует выбрать один вариант из нескольких предложенных. | Пиво Чай Кофе |
| reset | Кнопка для возвращения данных формы в первоначальное значение. | |
| submit | Кнопка для отправки данных формы на сервер. | |
| text | Текстовое поле. Предназначено для ввода символов с помощью клавиатуры. |
В HTML5 добавлены новые значения, представленные в табл. 2.
| Тип | Описание |
|---|---|
| color | Виджет для выбора цвета. |
| date | Поле для выбора календарной даты. |
| datetime | Указание даты и времени. |
| datetime-local | Указание местной даты и времени. |
| Для адресов электронной почты. | |
| number | Ввод чисел. |
| range | Ползунок для выбора чисел в указанном диапазоне. |
| search | Поле для поиска. |
| tel | Для телефонных номеров. |
| time | Для времени. |
| url | Для веб-адресов. |
| month | Выбор месяца. |
| week | Выбор недели. |
Поддержка этих значений браузерами показана в табл. 3.
Input type hidden что это
Value
Дополнительные признаки
Использование скрытых входов
Как упоминалось выше,скрытые входы могут быть использованы везде,где вы хотите включить данные,которые пользователь не может увидеть или отредактировать вместе с формой,когда она отправлена на сервер.Давайте рассмотрим некоторые примеры,которые иллюстрируют ее использование.
Отслеживание отредактированного содержимого
Одним из наиболее распространенных способов использования скрытых входных данных является отслеживание того,какие записи базы данных необходимо обновлять при отправке формы редактирования.Типичный рабочий процесс выглядит следующим образом:
Идея здесь заключается в том,что во время выполнения шага 2 идентификатор обновляемой записи хранится в скрытом виде.Когда форма отправляется в шаге 3,ID автоматически отправляется обратно на сервер с содержанием записи.ID позволяет серверному компоненту сайта точно знать,какая запись должна быть обновлена предоставленными данными.
Вы можете увидеть полный пример того, как это может выглядеть, в разделе « Примеры » ниже.
Улучшение безопасности веб-сайтов
Скрытые входы также используются для хранения и отправки токенов безопасности или секретов в целях повышения безопасности веб-сайта. Основная идея заключается в том, что если пользователь заполняет конфиденциальную форму, например форму на своем банковском веб-сайте, чтобы перевести деньги на другой счет, секрет, который им будет предоставлен, подтвердит, что они такие, какими они себя называют, и что они используют правильную форму для отправки запроса на перевод.
Это помешает злоумышленнику создать поддельную форму, выдать себя за банк и отправить форму по электронной почте ничего не подозревающим пользователям, чтобы обманом заставить их перевести деньги в неправильное место. Этот вид атаки называется подделкой межсайтовых запросов (CSRF) ; Практически любой авторитетный серверный фреймворк использует скрытые секреты для предотвращения таких атак.
Примечание. Размещение секрета на скрытом входе не делает его безопасным. Состав и кодировка ключа будут делать это. Значение скрытого ввода состоит в том, что он хранит секрет, связанный с данными, и автоматически включает его, когда форма отправляется на сервер. Вам нужно использовать хорошо продуманные секреты, чтобы действительно защитить свой сайт.
Validation
Скрытые входы не участвуют в валидации ограничений;они не имеют реальной ценности,которую можно было бы ограничить.
Examples
Давайте посмотрим, как мы могли бы реализовать простую версию формы редактирования, которую мы описали ранее (см. Отслеживание редактируемого содержимого ), используя скрытый ввод для запоминания идентификатора редактируемой записи.
HTML формы редактирования может выглядеть немного так:
Давайте также добавим несколько простых CSS:
Выход выглядит так:
После отправки данные формы,отправленные на сервер,будут выглядеть примерно так:
Несмотря на то,что скрытый вход вообще не виден,его данные все равно передаются.
Input type hidden что это
Если атрибут type не указан, то по умолчанию используется тип «text».
Поддержка браузеров
Синтаксис
Значение атрибута
| Значение | Описание |
|---|---|
| button | Определяет кликабельную кнопку (в основном используется с JavaScript для активации скрипта) |
| checkbox | Определяет флажок |
| color | Определяет выбор цвета |
| date | Определяет элемент управления датой (год, месяц, день (без времени)) |
| datetime-local | Определяет контроль даты и времени (год, месяц, день, время (без часового пояса) |
| Определяет поле для адреса электронной почты | |
| file | Определяет поле выбора файла и кнопку «Обзора» (для загрузки файлов) |
| hidden | Определяет скрытое поле ввода |
| image | Определяет изображение как кнопку отправки |
| month | Определяет контроль месяца и года (без часового пояса) |
| number | Определяет поле для ввода номера |
| password | Определяет поле пароля |
| radio | Определяет переключатель |
| range | Определяет элемент управления диапазоном (например, ползунок) |
| reset | Определяет кнопку сброса |
| search | Определяет текстовое поле для ввода строки поиска |
| submit | Определяет кнопку отправки |
| tel | Определяет поле для ввода телефонного номера |
| text | По умолчанию. Определяет однострочное текстовое поле |
| time | Определяет элемент управления для ввода времени (без часового пояса) |
| url | Определяет поле для ввода URL |
| week | Определяет контроль недели и года (без часового пояса) |
Еще примеры
Тип ввода: button
Кнопка, которая активирует JavaScript при нажатии на нее:
Тип ввода: checkbox
Флажки позволяют пользователю выбрать один или несколько вариантов из ограниченного числа вариантов:
У меня есть велосипед
У меня есть машина
Тип ввода: color
Выбрать цвет из палитры цветов:
Тип ввода: date
Определить дату контроля:
Тип ввода: datetime-local
Определить контроль даты и времени (без часового пояса):
Тип ввода: email
Определить поле для адреса электронной почты (будет автоматически проверяться при отправке):
Тип ввода: file
Определить поле выбора файла и кнопку «Обзор. » (для загрузки файлов):
Тип ввода: hidden
Определить скрытое поле (невидимое пользователю).
Скрытое поле часто хранит запись базы данных, которая должна быть обновлена при отправке формы:
Тип ввода: image
Определить изображение как кнопку отправки:
Тип ввода: month
Определить контроль месяца и года (без часового пояса):
Тип ввода: number
Определить поле для ввода номера (вы также можете установить ограничения на то, какие номера принимаются):
Для указания ограничений используйте следующие атрибуты:
Тип ввода: password
Определить поле пароля (символы маскируются):
Тип ввода: radio
Переключатели позволяют пользователю выбрать только один из ограниченного числа вариантов:
Тип ввода: range
Определить элемент управления для ввода числа, точное значение которого не имеет значения (например, ползунок). Диапазон по умолчанию от 0 до 100. Однако вы можете установить ограничения на то, какие числа принимаются с атрибутами min, max и step:
Для указания ограничений используйте следующие атрибуты:
Тип ввода: reset
Определить кнопку сброса (сброс всех значений формы к значениям по умолчанию):
Совет: Используйте кнопку сброса осторожно! Это может раздражать пользователей, которые случайно активируют кнопку сброса.
Тип ввода: search
Определить поле поиска (например, поиск по сайту или поиск в Google):
Тип ввода: submit
Определить кнопку отправки:
Тип ввода: tel
Определить поле для ввода телефонного номера:
Тип ввода: text
Определить два однострочных текстовых поля, в которые пользователь может вводить текст:
Тип ввода: time
Определите элемент управления для ввода времени (без часового пояса):
Тип ввода: url
Определить поле для ввода URL:
Тип ввода: week
Определите контроль недели и года (без часового пояса):
: The Input (Form Input) element
The 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 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.
types»> types
The available types are as follows:
| Type | Description | Basic Examples | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| button | A push button with no default behavior displaying the value of the value attribute, empty by default. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| color | A control for specifying a color; opening a color picker when active in supporting browsers. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| date | A control for entering a date (year, month, and day, with no time). Opens a date picker or numeric wheels for year, month, day when active in supporting browsers. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| datetime-local | A control for entering a date and time, with no time zone. Opens a date picker or numeric wheels for date- and time-components when active in supporting browsers. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| A field for editing an email address. Looks like a text input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| file | A control that lets the user select a file. Use the accept attribute to define the types of files that the control can select. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| hidden | A control that is not displayed but whose value is submitted to the server. There is an example in the next column, but it’s hidden! | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| image | A graphical submit button. Displays an image defined by the src attribute. The alt attribute displays if the image src is missing. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| number | A control for entering a number. Displays a spinner and adds default validation when supported. Displays a numeric keypad in some devices with dynamic keypads. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| password | A single-line text field whose value is obscured. Will alert user if site is not secure. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| radio | A radio button, allowing a single value to be selected out of multiple choices with the same name value. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| range | A control for entering a number whose exact value is not important. Displays as a range widget defaulting to the middle value. Used in conjunction min and max to define the range of acceptable values. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| reset | A button that resets the contents of the form to default values. Not recommended. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| search | A single-line text field for entering search strings. Line-breaks are automatically removed from the input value. May include a delete icon in supporting browsers that can be used to clear the field. Displays a search icon instead of enter key on some devices with dynamic keypads. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| tel | A control for entering a telephone number. Displays a telephone keypad in some devices with dynamic keypads. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| text | The default value. A single-line text field. Line-breaks are automatically removed from the input value. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| url | A field for entering a URL. Looks like a text input, but has validation parameters and relevant keyboard in supporting browsers and devices with dynamic keyboards. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| week | A control for entering a date consisting of a week-year number and a week number with no time zone. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Obsolete values | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| datetime | A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone. | AttributesThe element is so powerful because of its attributes; the type attribute, described with examples above, being the most important. Since every 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. This element includes the global attributes. Those with extra importance as it relates to are highlighted.
A few additional non-standard attributes are listed following the descriptions of the standard attributes. Individual attributesValid 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 scr 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 Values in The HTML autocomplete attribute for permitted values. See The HTML 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 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. 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.) 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 across page loads. Use the autocomplete attribute to control this feature. input ( type=hidden ) elementIf you don’t know what an element is or how you must use it, I recommend you read the «HTML tags and attributes» tutorial that you can find in the HTML tutorials section. DescriptionThe input element, having the «hidden» value in its type attribute, represents any abitrary text string that’s not supposed to be seen or edited by the user. Hidden inputs are specially useful to send data to the server defined by the author, based or not on user interaction. When the name attribute takes a case-insensitive version of the value «_charset_» the element instructs the browser to provide the character encoding used to send the form as value for the field. In such case, the value attribute must be omitted. The content of the value attribute in this element is usually static, but authors may employ scripts to change it as they see fit. ExamplesAttributesSpecific attributesautofocusA boolean value instructing the browser to set the focus to this control when the document has finished loading or when the dialog where the control finds itself is shown. If the attribute has the value «autofocus» or the empty string («»), or if it’s just present, the control should get the focus as soon as possible, after the page or dialog has been loaded. disabledA boolean value indicating wether the control is disabled or not. If the attribute takes the value «disabled» or the empty string («»), or if it’s just present, the control will be disabled. Disabled controls are rendered greyed out (if visible), are blocked from user interaction and, more importantly, their values (if any) aren’t sent when the form is submitted. The value of the id attribute of the form with which this control is associated to. A name for the control. This name will be sent by the browser to the processing agent, paired with the content of the value attribute. Both attributes together will conform a name-value pair that will be used to process the form data. Currently, the value isindex (formerly used in a special way by some browsers and included in the HTML standar) as well as the empty string, aren’t permitted in this attribute. When this attribute takes the special value _charset_ and the value attribute isn’t specified, the character encoding used in the form is automatically set as the content of the value attribute upon submission. A value indicating the type of the field that this element represents. There are twenty two possible values (case-insensitive): When this attribute isn’t present, the element behaves as it would have the value «text». valueA value for the control. This value will be sent by the browser to the processing agent, paired with the content of the name attribute. Both attributes together will conform a name-value pair that will be used to process the form data. Global attributesFor information about global attributes refer to this list of global attributes in HTML 5. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||



