What is the jQuery val method?

The $.val method in jQuery is used to set or get the value of the specified element.

If you use it to get the value of an element and there are multiple occurrences of that element, it will return first matched element values only.

See example of val  to get value

If you are using the $.val to set the value and there are multiple occurrences of matched elements then it will set values of all matched elements.

See example of val to set value

Generally, this method is used to retrieve the values form elements like text boxes, select-option dropdown, textarea etc.

The examples below will show you how to get and set values by using jQuery val method, first let us have a look at the syntax of val() method.

Syntax of val method

The basic syntax of val method to get value is:

$(“element”).val();

The syntax to set value is:

$(“element”).val(“Value to set”);

Example of getting select option dropdown value using val

The following example shows how to get the value of select-option dropdown. We have a dropdown with a few color options. As you select a color and click on the button “Show selected option value”, an alert will show the value of selected option.

Experience this example online

Example of getting textbox value by val

The example below shows getting the value of a text box. Enter any text into the given text box and press “Show value” button. It will show an alert with the entered text.

Experience this example online

Example of setting value with jQuery val method

The following example shows how to set the value by using the val jQuery method.

For this example, we will use input boxes. At page loading, the $.val method is used to set the values. If you click on the button, a new value will be set in the input boxes.

Experience this example online

 

Useful reading: jQuery slide | jQuery hover