🚨 Get Your Free NFT Certificate Mint by Completing the Web3 Exam! START NOW

Code has been added to clipboard!

jQuery .val(): Set or Get the Attribute Value of Form Elements

Reading time 1 min
Published Jan 24, 2018
Updated Sep 27, 2019

jQuery val: Main Tips

  • jQuery .val() sets or returns the attribute value of the matched HTML elements.
  • Usually, the jQuery .val() method deals with the values of form elements.

Using .val()

The jQuery .val() function assigns or returns the attribute value of specified elements. Check the example below to see a jQuery input value assigned to a text field upon clicking a button:

$("button").click(() => {
    $("input:text").val("Ben Johnson");

Note: when the collection is empty, jQuery input value is returned as undefined.

To make jQuery get input value, you don't need to define any arguments:


Now, to make jQuery set input value, either a new value or a function that returns it must be specified:



Note: if you choose to add a function, remember that since jQuery 1.4, it receives two arguments - the position of the element and its value before the change.