Type hidden html что это
Перейти к содержимому

Type hidden html что это

  • автор:

<input type="hidden">

<input> elements of type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. For example, the ID of the content that is currently being ordered or edited, or a unique security token. Hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page’s content.

Note: The input and change events do not apply to this input type. Hidden inputs cannot be focused even using JavaScript (e.g. hiddenInput.focus() ).

Value

The <input> element’s value attribute holds a string that contains the hidden data you want to include when the form is submitted to the server. This specifically can’t be edited or seen by the user via the user interface, although you could edit the value via browser developer tools.

Warning: While the value isn’t 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 rely on hidden inputs as a form of security.

Additional attributes

In addition to the attributes common to all <input> elements, hidden inputs offer the following attributes.

This is actually one of the common attributes, but it has a special meaning available for hidden inputs. Normally, the name attribute functions on hidden inputs just like on any other input. However, when the form is submitted, a hidden input whose name is set to _charset_ will automatically be reported with the value set to the character encoding used to submit the form.

Using hidden inputs

As mentioned above, hidden inputs can be used anywhere that you want to include data the user can’t see or edit along with the form when it’s submitted to the server. Let’s look at some examples that illustrate its use.

Tracking edited content

One of the most common uses for hidden inputs is to keep track of what database record needs to be updated when an edit form is submitted. A typical workflow looks like this:

  1. User decides to edit some content they have control over, such as a blog post, or a product entry. They get started by pressing the edit button.
  2. The content to be edited is taken from the database and loaded into an HTML form to allow the user to make changes.
  3. After editing, the user submits the form, and the updated data is sent back to the server to be updated in the database.

The idea here is that during step 2, the ID of the record being updated is kept in a hidden input. When the form is submitted in step 3, the ID is automatically sent back to the server with the record content. The ID lets the site’s server-side component know exactly which record needs to be updated with the submitted data.

You can see a full example of what this might look like in the Examples section below.

Improving website security

Hidden inputs are also used to store and submit security tokens or secrets, for the purposes of improving website security. The basic idea is that if a user is filling in a sensitive form, such as a form on their banking website to transfer some money to another account, the secret they would be provided with would prove that they are who they say they are, and that they are using the correct form to submit the transfer request.

This would stop a malicious user from creating a fake form, pretending to be a bank, and emailing the form to unsuspecting users to trick them into transferring money to the wrong place. This kind of attack is called a Cross Site Request Forgery (CSRF); pretty much any reputable server-side framework uses hidden secrets to prevent such attacks.

Note: Placing the secret in a hidden input doesn’t inherently make it secure. The key’s composition and encoding would do that. The value of the hidden input is that it keeps the secret associated with the data and automatically includes it when the form is sent to the server. You need to use well-designed secrets to actually secure your website.

Validation

Hidden inputs don’t participate in constraint validation; they have no real value to be constrained.

Examples

Let’s look at how we might implement a simple version of the edit form we described earlier (see Tracking edited content), using a hidden input to remember the ID of the record being edited.

The edit form’s HTML might look a bit like this:

Let’s also add some simple CSS:

The server would set the value of the hidden input with the ID » postID » to the ID of the post in its database before sending the form to the user’s browser and would use that information when the form is returned to know which database record to update with modified information. No scripting is needed in the content to handle this.

The output looks like this:

Note: You can also find the example on GitHub (see the source code, and also see it running live).

When submitted, the form data sent to the server will look something like this:

Even though the hidden input cannot be seen at all, its data is still submitted.

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 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 type=»hidden»>

<input> Элементы <input> типа hidden позволяют веб-разработчикам включать данные, которые не могут быть просмотрены или изменены пользователями при отправке формы. Например, идентификатор контента, который в настоящее время заказывается или редактируется, или уникальный токен безопасности. Скрытые поля ввода полностью невидимы на отображаемой странице, и нет способа сделать их видимыми в содержимом страницы.

Примечание. События input и change не применяются к этому типу ввода. Скрытые входы не могут быть сфокусированы даже с использованием JavaScript (например, hiddenInput.focus() ).

Value

Атрибут value элемента <input> содержит строку, содержащую скрытые данные, которые вы хотите включить при отправке формы на сервер. Это конкретно не может быть отредактировано или просмотрено пользователем через пользовательский интерфейс, хотя вы можете изменить значение с помощью инструментов разработчика браузера. value

Предупреждение. Хотя значение не отображается пользователю в содержимом страницы, оно отображается и может быть отредактировано с помощью инструментов разработчика любого браузера или функции «Просмотр исходного кода». Не полагайтесь на hidden данные как на форму безопасности.

Additional attributes

В дополнение к атрибутам, общим для всех элементов <input> , hidden входы предлагают следующие атрибуты.

На самом деле это один из общих атрибутов, но он имеет особое значение, доступное для скрытых входных данных. Обычно атрибут name работает со скрытыми входами так же, как с любым другим входом. Однако при _charset_ формы скрытый ввод, name которого установлено на _charset_, будет автоматически сообщен со значением, установленным в кодировке символов, используемой для отправки формы.

Использование скрытых входов

Как упоминалось выше,скрытые входы могут быть использованы везде,где вы хотите включить данные,которые пользователь не может увидеть или отредактировать вместе с формой,когда она отправлена на сервер.Давайте рассмотрим некоторые примеры,которые иллюстрируют ее использование.

Отслеживание отредактированного содержимого

Одним из наиболее распространенных способов использования скрытых входных данных является отслеживание того,какие записи базы данных необходимо обновлять при отправке формы редактирования.Типичный рабочий процесс выглядит следующим образом:

  1. Пользователь решает отредактировать некоторое содержание,над которым он имеет контроль,например,запись в блоге или запись о продукте.Он начинает редактирование с нажатия кнопки редактирования.
  2. Редактируемое содержимое берётся из базы данных и загружается в HTML-форму,чтобы пользователь мог вносить изменения.
  3. После редактирования пользователь отправляет форму,а обновленные данные отправляются обратно на сервер для обновления в базе данных.

Идея здесь заключается в том,что во время выполнения шага 2 идентификатор обновляемой записи хранится в скрытом виде.Когда форма отправляется в шаге 3,ID автоматически отправляется обратно на сервер с содержанием записи.ID позволяет серверному компоненту сайта точно знать,какая запись должна быть обновлена предоставленными данными.

Вы можете увидеть полный пример того, как это может выглядеть, в разделе « Примеры » ниже.

Улучшение безопасности веб-сайтов

Скрытые входы также используются для хранения и отправки токенов безопасности или секретов в целях повышения безопасности веб-сайта. Основная идея заключается в том, что если пользователь заполняет конфиденциальную форму, например форму на своем банковском веб-сайте, чтобы перевести деньги на другой счет, секрет, который им будет предоставлен, подтвердит, что они такие, какими они себя называют, и что они используют правильную форму для отправки запроса на перевод.

Это помешает злоумышленнику создать поддельную форму, выдать себя за банк и отправить форму по электронной почте ничего не подозревающим пользователям, чтобы обманом заставить их перевести деньги в неправильное место. Этот вид атаки называется подделкой межсайтовых запросов (CSRF) ; Практически любой авторитетный серверный фреймворк использует скрытые секреты для предотвращения таких атак.

Примечание. Размещение секрета на скрытом входе не делает его безопасным. Состав и кодировка ключа будут делать это. Значение скрытого ввода состоит в том, что он хранит секрет, связанный с данными, и автоматически включает его, когда форма отправляется на сервер. Вам нужно использовать хорошо продуманные секреты, чтобы действительно защитить свой сайт.

Validation

Скрытые входы не участвуют в валидации ограничений;они не имеют реальной ценности,которую можно было бы ограничить.

Examples

Давайте посмотрим, как мы могли бы реализовать простую версию формы редактирования, которую мы описали ранее (см. Отслеживание редактируемого содержимого ), используя скрытый ввод для запоминания идентификатора редактируемой записи.

HTML формы редактирования может выглядеть немного так:

Давайте также добавим несколько простых CSS:

Сервер установит значение скрытого ввода с идентификатором postID равным идентификатору сообщения в своей базе данных перед отправкой формы в браузер пользователя и будет использовать эту информацию при возврате формы, чтобы знать, какую запись базы данных нужно обновить. с измененной информацией. Чтобы справиться с этим, в контенте не требуется никаких сценариев.

Выход выглядит так:

Примечание. Вы также можете найти пример на GitHub (см. исходный код , а также посмотреть, как он работает вживую ).

После отправки данные формы,отправленные на сервер,будут выглядеть примерно так:

Несмотря на то,что скрытый вход вообще не виден,его данные все равно передаются.

HTML <input type="hidden">

The <input type="hidden"> defines a hidden input field.

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!

Browser Support

The numbers in the table specify the first browser version that fully supports the element.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *