jQuery Attribute Operations - val() Method

Example

Set the value of the input field:

$("button").click(function(){
  $":text)。val("Hello World");
});

Try It Yourself

Definition and Usage

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

The value of the element is set through the value attribute. This method is mostly used for input elements.

If this method does not set any parameters, it returns the current value of the selected element.

Syntax

$(selector).val(value)
Parameters Description
value - Optional. Specifies the new content for the selected element.

Returns Value Attribute

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

Syntax

$(selector).val()

Try It Yourself

Set the Value attribute's value

$(selector).val(value)
Parameters Description
value Set the Value attribute's value.

Try It Yourself

Use a function to set the Value attribute's value

$(selector).val(function(index,oldvalue))

Try It Yourself

Parameters Description
function(index,oldvalue)

Specifies the function to return the value to be set.

  • index - Optional. Accepts the index position of the selector.
  • oldvalue - Optional. Accepts the current Value attribute of the selector.