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:-
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
1 2 3 4 5 6 7 8 |
<script> $(document).ready(function(){ $('button').click(function(){ var myvalue = $( "input" ).val(); alert(myvalue); }); }); </script> |
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
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $( ".mysetinput" ).val("Tutorialdeep"); }); }); </script> <button type="button" class="mysetbtn">Click to Set Value Attribute</button><br><br> <input type="text" class="mysetinput"> |
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
1 2 3 4 5 6 7 8 9 10 11 |
<script> $(document).ready(function(){ $('.myfnsetbtn').click(function(){ $( ".myfnsetinput" ).val(function(n, p){ return p + "Tutorialdeep"; }); }); }); </script> <button type="button" class="myfnsetbtn">Click to Use Function Set Value Attribute</button><br><br> <input type="text" class="myfnsetinput" value="Learn jQuery from "> |
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