jQuery val() Method

Last Updated:

jQuery val() Method

The jQuery val() method gets or sets the value attribute of the selected elements.

Note: The following points to be considered when using the jQuery val() method

  • When this method is used to get value, it gets the value of the value attribute of the first matched element.
  • When this method is used to set value, it will overwrite all matched elements.

In the following example, we will get the value of the value attribute of the <input> tag.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery val() Method</h1> <input type="text" value="Hello jQuery"> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ alert($("input").val()); }); }); </script> </body> </html>

Syntax

// Get content $(selector).val(); // Set content $(selector).val(value); // Set content using a function $(selector).val(func);

Parameter Values

Value Explanation
value Specifies a string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.
func Specifies a function returning the value to set. this is the current element.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
val()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set Value

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery val() Method</h1> <input type="text"> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ $("input").val("Hello jQuery"); }); }); </script> </body> </html>

Set Value using Function

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery val() Method</h1> <input type="text"> <button>Click Me</button> <p></p> <script> $(document).ready(function(){ $("button").click(function(){ $("input").val(function(){ var txt = "Hello jQuery"; return txt; }); }); }); </script> </body> </html>

Share this Page

Meet the Author