English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery val() Method

jQuery HTML/CSS Methods

The val() method is used to get or set the attribute value of the selected FORM element.

Use the val() methodGetWhen setting the attribute value, it returnsThe first selected elementvalue.

Use the val() methodSetWhen setting the attribute value, it will overrideAll selected elementsvalue.

Note: The val() method is mainly used to get the value of FORM elements, such as input, select, and textarea.

Syntax:

Get the value attribute:

$.val()

Set the value attribute:

$.val(value)

Use a function to set the value attribute:

$.val(function(index, currentValue))

Example

Get the value of the <input> field:

$("button").click(function(){
  $("input:text").val();
});
Test and see‹/›

Set the value of the <input> field:

$("button").click(function(){
  $("input").val("Hello world");
});
Test and see‹/›

Use a function to change the value of an element:

$("button").click(function(){
  $("input:text").val(function(i, val){
    return val + " Hello";
  });
});
Test and see‹/›

Parameter Value

ParameterDescription
valueFor the values of all selected elements
Note:If this parameter is omitted, the val() will return the value property of the first selected element
function(index, currentValue)Specify a function that returns the value to be set
  • index-Return the index position of the element in the collection

  • currentContent-Return the current value of the selected element

jQuery HTML/CSS Methods