We can set a hidden field value in a form in JavaScript by changing the type property of the field with the help of the getElementById() method.

document.getElementById("someField").type = "hidden";

The above code would change the property type to hidden.

Let’s take a look at an example below:


Let’s say we have the following HTML form:

As you can see in the code above, we have two simple text input fields.

If we wanted to hide the input field for Full Name, we would use the following JavaScript code:

document.getElementById("fname").type = "hidden";

It can be very useful to hide form fields from the user. Just note that when a form field has the type of hidden, it will not be able to be seen on the webpage by the user. However, the user could still access the information in the hidden field with the use of a browser inspector that most browsers have. So you should make sure not to store any data in the hidden field that you do not want someone to have access to.

Example of Setting an Input Field Value to Hidden In JavaScript

In this simple example, we will just have a standard HTML form. We will provide the HTML code for it and let the user enter a name and submit the form. The form will not have any backend connected to it, so when you submit the form, it should just refresh the page and put the name variable you entered in the URL.

The form you will see will only show a name field, its label, and a submit button. But there is also a hidden email field. We have added JavaScript code to this page to hide the field right away.

Here is that JavaScript code:

document.getElementById("email").type = "hidden";

Here is the form for you to see with the hidden email field:





And here is the Full Code and JavaScript:

Hopefully this article has been useful for you to understand how to set a hidden field value in JavaScript.

Categorized in:

JavaScript,

Last Update: March 22, 2024