- input ( type=hidden ) element
- Description
- Examples
- Attributes
- Specific attributes
- autofocus
- disabled
- form
- name
- type
- value
- Global attributes
- Events
- Global events
- Tutorials
- Reference
- Html hidden post data
- Value
- Additional attributes
- name
- Using hidden inputs
- Tracking edited content
- Improving website security
- Validation
- Examples
- Technical summary
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Скрытое поле
input ( type=hidden ) element
If 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.
Description
The 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.
Examples
In the next example we’ll create a form with a text input control and a couple of hidden fields. As you will see, the hidden fields are not visible nor interactive in the redered document, but the value they hold will be, nevertheless, sent to the server. This you’ll be able to confirm in the results page when you submit the form .
action="../../form-result.php" method="post" target="_blank"> Some text: type="text" name="sometext"> type="hidden" name="_charset_"> type="hidden" name="location" value="input-hidden-page"> type="submit" value="Send data">
Attributes
Specific attributes
autofocus
A 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.
type="hidden" name="state" value="login" autofocus>
disabled
A 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.
action="../../form-result.php" method="post" target="_blank"> Some text: type="text" name="sometext" disabled> type="hidden" name="location" value="input-hidden-page" disabled> type="submit" value="Send data">
form
The value of the id attribute of the form with which this control is associated to.
This attribute is new in HTML 5 and helps defining the pertenence of controls in nested or distant forms.
>"form1" action="../../form-result.php" method="post" target="_blank"> type="hidden" name="dataname" value="datavalue"> type="submit" value="Send data" form="form1">
name
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.
action="../../form-result.php" method="post" target="_blank"> type="hidden" name="_charset_"> type="hidden" name="dataname" value="datavalue"> type="submit" value="Send data">
type
A value indicating the type of the field that this element represents. There are twenty two possible values (case-insensitive):
- hidden: a hidden control used to send information to the server, typically managed by scripts.
- text: a control used to input a single-line piece of text.
- search: same as text but for search purposes.
- tel: a control used to provide a telephone number.
- url: a text box used to input a single and absolute URL .
- email: a control designed to edit one or more e-mail addresses.
- password: a text box for editing passwords, where the characters are represented by dots.
- date: a control to input a specific date.
- month: a control to input a specific month.
- week: a control to input a specific week.
- time: a control to input a specific time.
- datetime-local: a control to input a specific local date and time.
- number: a control to input a number.
- range: a control to input one or two numbers inside a range.
- color: a control to input a color.
- checkbox: a control to input a boolean value (true/false).
- radio: a control used to choose one single option among many.
- file: a control used to upload files to the server.
- submit: a button used to submit the form.
- image: same as submit but with the ability to be shown as an image instead of using the default button appearance.
- reset: a button used to reset the form’s controls to their default values.
- button: a button with no default action associated.
When this attribute isn’t present, the element behaves as it would have the value «text».
type="hidden" name="dataname" value="datavalue">
value
A 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.
action="../../form-result.php" method="post" target="_blank"> type="hidden" name="dataname" value="datavalue"> type="submit" value="Send data">
Global attributes
For information about global attributes refer to this list of global attributes in HTML 5.
Events
Global events
For information about global events refer to this list of global events in HTML 5.
Tutorials
Reference
Html hidden post data
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 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
name
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:
- 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.
- The content to be edited is taken from the database and loaded into an HTML form to allow the user to make changes.
- 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:
form> div> label for="title">Post title:label> input type="text" id="title" name="title" value="My excellent blog post" /> div> div> label for="content">Post content:label> textarea id="content" name="content" cols="60" rows="5"> This is the content of my excellent blog post. I hope you enjoy it! textarea> div> div> button type="submit">Update postbutton> div> input type="hidden" id="postId" name="postId" value="34657" /> form>
Let’s also add some simple CSS:
html font-family: sans-serif; > form width: 500px; > div display: flex; margin-bottom: 10px; > label flex: 2; line-height: 2; text-align: right; padding-right: 20px; > input, textarea flex: 7; font-family: sans-serif; font-size: 1.1rem; padding: 5px; > textarea height: 60px; >
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.
Technical summary
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Mar 13, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Скрытое поле
Часто возникает ситуация, когда требуется передать в форме некоторые промежуточные данные, которые не должны изменяться пользователем. Более того, такие данные не должны показываться пользователю, поскольку носят технический характер и обычно служат для передачи некоторой информации от страницы к странице. Для этой цели применяется скрытое поле, оно не отображается на странице и прячет своё содержимое от пользователя. Посетитель не может в него ничего внести или напечатать.
Синтаксис создания скрытого поля.
Атрибуты перечислены в табл. 1.
Атрибут | Описание |
---|---|
name | Имя поля для его идентификации обработчиком формы. |
value | Значение поля, определяющее, какая информация будет отправлена на сервер. |
Пример использования скрытых полей приведен в примере 1.
Пример 1. Использование скрытого поля
Напишите любимое слово и нажмите кнопку Отправить (никакие данные не будут передаваться на сервер!):
В данном примере показано создание двух скрытых полей, одно из них носит имя name и получает значение Vasya , а второе именуется password со значением pupkin . В результате отправки формы обработчику, указанному в атрибуте action , программа может легко прочитать эти данные и интерпретировать их по усмотрению разработчика.