- Html forms data types
- Контекст Использования
- Атрибуты
- DOM_interface
- Примеры
- Совместимость браузера
- Смотрите также
- Found a content problem with this page?
- HTML Input Types
- HTML Input Types
- Input Type Text
- Example
- Input Type Password
- Example
- Input Type Submit
- Example
- Example
- Input Type Reset
- Example
- Input Type Radio
- Example
- Input Type Checkbox
- Example
- Input Type Button
- Example
- Input Type Color
- Example
- Input Type Date
- Example
- Example
- Input Type Datetime-local
- Example
- Input Type Email
- Example
- Input Type Image
- Example
- Input Type File
- Example
- Input Type Hidden
- Example
- Input Type Month
- Example
- Input Type Number
- Example
- Input Restrictions
- Example
- Input Type Range
- Example
- Input Type Search
- Example
- Input Type Tel
- Example
- Input Type Time
- Example
- Input Type Url
- Example
- Input Type Week
Html forms data types
Элемент HTML form ( ) представляет (собой) раздел документа, содержащий интерактивные элементы управления, которые позволяют пользователю отправлять информацию на веб-сервер.
Можно использовать :valid (en-US) и :invalid (en-US) CSS псевдоклассы для стилизации элемента, в зависимости от того, валиден или нет конкретный элемент elements внутри формы.
Контекст Использования
Категория содержимого | Flow content (en-US) |
---|---|
Разрешённое содержимое | Flow content (en-US) , но не содержащий элементов |
Пропуск тега | Нет. И открывающий и закрывающий тег должны быть. |
Нормативный документ | HTML5, section 4.10.3 (HTML4.01, section 17.3) |
Атрибуты
Как и все HTML-элементы, этот элемент поддерживает глобальные атрибуты (en-US) .
Список типов содержимого, разделённых запятой, которые принимает сервер.
Примечание: Этот атрибут был удалён в HTML5 и его не следует больше использовать. Взамен, используйте accept атрибут заданного элемента.
Разделённые пробелами символьные кодировки, которые принимает сервер. Браузер использует их в том порядке, в котором они перечислены. Значение по умолчанию означает ту же кодировку что и у страницы. (В предыдущей версии HTML, различные кодировки могли быть разделены запятыми.)
URI-адрес программы, которая обрабатывает информацию переданную через форму. Это значение может быть переписано с помощью атрибута formaction на или элементе.
Указывает, могут ли элементы управления автоматически быть дописаны в форме браузером. Эта настройка может быть переписана с помощью атрибута autocomplete на элементе формы. Возможные значения:
- off : Пользователь должен явно ввести значение в каждое поле или документ предоставит свой собственный метод автодополнения; браузер автоматически не дополняет записи.
- on : Браузер может автоматически дополнить значения, основанные на значениях, которые пользователь уже вводил, в течение предыдущего использования формы.
**Примечание:**Если вы установили значение off для autocomplete атрибута формы, из-за того, что документ предоставляет своё собственное автодополнение, то вам следует также установить значение off для autocomplete каждого элемента формы, которые документ может автоматически дополнить. Подробнее, смотрите Google Chrome notes.
Когда значение атрибута method равно post , атрибут — MIME тип содержимого, которое используется, чтобы передать форму на сервер. Возможные значения:
- application/x-www-form-urlencoded : Значение по умолчанию, если атрибут не задан.
- multipart/form-data : Используйте это значение, если пользуетесь элементом атрибутом type установленным в «file».
- text/plain (HTML5) Это значение может быть переписано атрибутом formenctype на элементе или .
HTTP (en-US) метод, который браузер использует, для отправки формы. Возможные значения:
- post : Соответствует HTTP POST методу ; данные из формы включаются в тело формы и посылаются на сервер.
- get : Соответствует GET методу; данные из формы добавляются к URI атрибута action , их разделяет ‘?’, и полученный URI посылается на сервер. Используйте этот метод, когда форма содержит только ASCII символы и не имеет побочного эффекта.Это значение может быть переписано атрибутом formmethod на или элементе.
Имя формы. В HTML 4 его использование запрещено ( id следует использовать взамен). Оно должно быть уникальным и не пустым среди всех форм в документе в HTML 5.
Это Boolean атрибут показывает, что форма не проверяется на валидность, когда отправляется серверу. Если атрибут пропущен (и поэтому форма проверяется), эта настройка по умолчанию, может быть переписана атрибутом formnovalidate на или элементе, принадлежащем форме.
Имя или ключевое слово, показывающее где отображать ответ, который будет получен, после отправки формы. В HTML 4, это имя или ключевое слово для фрейма. В HTML5, это имя или ключевое слово, контекста просмотра (например, вкладка, окно, или линейный фрейм). Следующие ключевые слова имеют специальное значение:
- _self : Загружает ответ в том же самом фрейме HTML 4 (или HTML5 контексте просмотра) как текущий. Это значение по умолчанию, если атрибут не указан.
- _blank : Загружает ответ в новом безымянном окне HTML 4 или HTML5 контексте просмотра.
- _parent : Загружает ответ HTML 4 в родительском наборе фрейма для текущего фрейма или HTML5 родительский контекст просмотра для текущего просмотра. Если нет предка, эта опция действует точно так же как as _self .
- _top : HTML 4: Загружает ответ в полное, оригинальное окно, закрывая все другие фреймы. HTML5: Загружает ответ в верхний уровень контекста просмотра (т.е., контекст просмотра это предок текущего и не имеет других предков). Если нет предка, эта опция действует точно так же как as _self .HTML5: Это значение может быть перезаписано formtarget атрибутом на или элементе.
DOM_interface
Этот элемент реализует HTMLFormElement интерфейс.
Примеры
form action=""> label for="GET-name">Name:label> input id="GET-name" type="text" name="name"> input type="submit" value="Save"> form> form action="" method="post"> label for="POST-name">Name:label> input id="POST-name" type="text" name="name"> input type="submit" value="Save"> form> form action="" method="post"> fieldset> legend>Titlelegend> input type="radio" name="radio" id="radio"> label for="radio">Click melabel> fieldset> form>
Совместимость браузера
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 17 июл. 2023 г. by MDN contributors.
Your blueprint for a better internet.
HTML Input Types
This chapter describes the different types for the HTML element.
HTML Input Types
Here are the different input types you can use in HTML:
Tip: The default value of the type attribute is «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
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
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
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
defines a radio button.
Radio buttons let a user select ONLY ONE of a limited number of choices:
Example
Choose your favorite Web language:
This is how the HTML code above will be displayed in a browser:
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
defines a button:
Example
This is how the HTML code above will be displayed in a browser:
Input Type Color
The 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 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 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 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 defines an image as a submit button.
The path to the image is specified in the src attribute.
Example
Input Type File
The defines a file-select field and a «Browse» button for file uploads.
Example
Input Type Hidden
The 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 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 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 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 is used for search fields (a search field behaves like a regular text field).
Example
Input Type Tel
The is used for input fields that should contain a telephone number.
Example
Input Type Time
The 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 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 allows the user to select a week and year.
Depending on browser support, a date picker can show up in the input field.