jQuery val() Function: Get or Set Value of Element

The jQuery val() method can be used to return or set the value attribute of the selected element. You can use this method for the elements inside the form tag to get or assign a value to them.

jQuery val() method

Syntax

There are three syntax of this method which are given below:-

Syntax to Return the Value Attribute
$(selector).val()
Syntax to Set the Value Attribute
$(selector).val(value)
Syntax to Set the Value Attribute Using Function
$(selector).val(function(index, current_value))

Description of the Parameters

The description of the parameters are given below.

Parameter Name Description
selector The selector is used to select the elements inside a form to get or set the value attribute. It uses the tag name, class name, or id of the elements to select.
value Specify the value of the value attribute for the selected elements to return or set.
index It returns the position of the index for the selected element.
current_value It returns the current value of the value attribute for the selected elements.

Examples of jQuery val() Method

Get Value of Input Element

If you want to get or return the value attribute of the selected elements, use the val() function without any argument as given below. The example contains the input box and the button for the click event.

Example 1

Test it Live

Output



Click the button given above to get the value attribute of the selected input element. It displays the value of the value attribute in the alert box.

Set Value of an Element

You can also use this method to set the value of the value attribute for the selected elements. To assign a value, you have to pass the value as the parameter of the jQuery val(). See the example given below.

Example 2

Test it Live

Output



Initially, there is no value assigned to the input element. You have to click the button given above to assign or set the value. It adds a value you want to set for the selected form input element.

Use Function to Set Value Attribute of an Element

In addition to all the above, you can also set the value attribute using the function. The function sets the value using the index position for the selected element. See the example given below to learn this.

Example 3

Test it Live

Output



When you click the button given above, it appends a value after the old value of the value attribute.

You may also like to read