There are two usage of jQuery val() method.
Syntax:
$(selector).val()
It is used to get value.
$(selector).val(value)
It is used to set value.
$(selector).val(function(index,currentvalue))
It is used to set value using function.
Parameter | Description |
---|---|
Value | It is a mandatory parameter. It is used specify the value of the attribute. |
Function (index, currentvalue) | It is an optional parameter. It is used to specify a function that returns the value to set. |
The val() method is primarily used to get the values of form elements. This method doesn't accept any arguments. This method returns a NULL when no option is selected and it returns an array containing the value of each selected options in the case of one or more selection.
Let's see the example of val() method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>val demo</title> <style> p { color: red; margin: 4px; } b { color: blue; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p></p> <select id="single"> <option>Single</option> <option>Double</option> <option>Triple</option> </select> <script> function displayVals() { var singleValues = $( "#single" ).val(); $( "p" ).html( "<b>Value:</b> " + singleValues); } $( "select" ).change( displayVals ); displayVals(); </script> </body> </html>
Output:
Let's see example of jQuery val() method with single and multiple select boxes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>val demo</title> <style> p { color: red; margin: 4px; } b { color: blue; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p></p> <select id="single"> <option>Single</option> <option>Single2</option> <option>Single3</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option>Multiple3</option> </select> <script> function displayVals() { var singleValues = $( "#single" ).val(); var multipleValues = $( "#multiple" ).val() || []; $( "p" ).html( "<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.join( ", " ) ); } $( "select" ).change( displayVals ); displayVals(); </script> </body> </html>
Output:
This method is used to set a string of text, a number, an array of strings corresponding to the value of each matched element. This method facilitates you to set the value by passing in the function.
Let's see the example of val(value) method.
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("input:text").val("rookienerd"); }); }); </script> </head> <body> <p>Name: <input type="text" name="user"></p> <button>Set the value of the input field</button> </body> </html>
Output:
Name: