Example

Set the value of an input field:

$("button").click(function(){
  $("input:text").val("Glenn Quagmire");
});

Try it yourself »

Definition and Usage

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

Note: This function is mostly used with form elements.


Return the Value Attribute

Returns the value of the value attribute of the FIRST matched element.

Syntax

$(selector).val()
Try it yourself »


Set the Value Attribute

Sets the value of the value attribute for ALL selected elements.

Syntax

$(selector).val(value)
Try it yourself »

Parameter Description
value Specifies the value of the value attribute


Set the Value Attribute Using a Function

Using a function to set the value of the value attribute for all selected elements.

Syntax

$(selector).val(function(index,oldvalue))
Try it yourself »

Parameter Description
function(index,oldvalue) Specifies a function that returns the value to set.
  • index - Optional. Receives the index position of the selector
  • oldvalue - Optional. Receives the current value attribute of the selector