jQuery val() method can either be used to get the current value of the first element in the set of matched elements or to set the value of every matched element.
jQuery val() sets or returns the value attribute of the selected elements.
Syntax:
When it is used to get value.
$(selector).val()
When it is used to set value.
$(selector).val(value)
Value: Value is a compulsory parameter, used to specify the value of the attribute.
When it is used to set value by calling function.
$(selector).val(function (index, currentvalue))
Function: It is an optional parameter that returns the new value on calling.
Index: It is passed as an argument inside the function to show the index position of the element.
Current value: This is another argument passed inside the function to show the current value of the selected element.
Example:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <p></p> <select id="single"> <option>Single</option> <option>Double</option> <option>Triple</option> </select> <script> function displayVals() { var singleValues = ( "p" ).html( "<b>Value:</b> " + singleValues); } $( "select" ).change( displayVals ); displayVals(); </script> </body> </html>