Hello guys, in the last tutorial, we learned about how to get the hidden field value in jquery with the help of the
Now in this tutorial, we will learn how to set the value of the hidden field in jquery. To set the hidden field value we will use the same
val() method having value as a parameter.
Let’s get started!!!
Set Hidden Field Value in jQuery
We will use the
val() method of jquery to set the value of fields. The
val() method is used to get or set the value of the input field in jquery.
You can get and set any type of input field’s value using this val() method, like text, textarea, radio, checkbox, search, etc.
Let’s have a look at some ways to set the value for the input hidden field in jquery.
Set Hidden Field Value By Id In jQuery
In this method, we will use the
id of the input field as a selector to target the field and set the value of that field. The id name of that field could be anything just referencing it.
For example, let’s take a simple HTML code of input type hidden, text, search, or any field with an id attribute. Also, take one button to trigger the event to set the value.
Now we will write jquery code to first get the value of the input text field. Then set the value of the input hidden field by clicking on the button.
In the above code, we made an on-click function to get the value of the text field and set that value into a hidden field with the
Set Hidden Field Value By name In jQuery
Now we will use the
name attribute of the input field to set its value. We will target the input field with a
name attribute selector and then set the value.
We take the same HTML example code having two input fields, one is a text field and another is a hidden field and yes one button for the click function.
You can see in the above code, we have used the name attribute to get the value of the text field and then set the value input type hidden field with the
val() method. You can modify the code as you want.
Set Hidden Field Value By type In jQuery
You can also use the
type attribute to target the input field to set the value in it. You just have to replace the name attribute from the above example with the type attribute. Let’s see the example code.
Let’s write the jquery code to get the value from the text input field and then set the value in the hidden input field by targetting with the type attribute.
You can see in the above code, we have gotten the value of the text field by id and then set the value with the
val() method to the hidden field.
Note: If you have more than one same type of input field and then don’t use this method to set the value, because the same value is set up for other fields too.
See Also: How to Get Hidden Field Value in jQuery?