jQuery val() Method

You are Here:

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

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

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>

Reminder

Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in jQuery.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author