jQuery val() is used to return or set the value of selected elements.
When val() method is used to return value, it returns the value of the first element from the selected elements.
Syntax of val() method when it is used for get value:
$(selector).val()
When val() method is used to set the value, it sets the value of all the selected elements.
Syntax of val() method when it is used for set value:
$(selector).val(content)
Note: While returning value it returns the value of first matched element, however when it is used for setting up the value of elements, it sets the value for all the matched elements.
Example 1: jQuery val() method – return value
In this example, we have a form with three input fields. We are using val()
method to get the value of input text fields. It returned the value of name (First text field) but ignored the value of second and third text field. This is what we discussed in the beginning that it returns the value of first matched element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("input:text").val());
});
});
</script>
</head>
<body>
Name: <input type="text" name="name" value="Steve"><br>
Emp ID: <input type="text" name="fname" value="E101"><br>
Address: <input type="text" name="address" value="New York"><br><br><br>
<button>Return the value of the first input text field</button>
</body>
</html>
Output:
Before button click:
After button click:
Example 2: jQuery val() method – Set value
In this example, we are using val() method to set the value of a text field.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:text").val("BeginnersBook.com");
});
});
</script>
</head>
<body>
<p>Website Name: <input type="text" name="web"></p>
<button>Set the value of the input text field</button>
</body>
</html>
Output:
Before button click:
After button click: