val() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:val

Description

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

When returning value, it returns the value of the value attribute of the FIRST matched element.

When setting value, it sets the value of the value attribute for ALL matched elements.

Syntax

ParameterRequire Description
valueRequired. the value of the value attribute
function(index,currentvalue) Optional. a function that returns the value to set.
  • index - Returns the index position of the element in the set
  • currentvalue - Returns the current value attribute of selected elements

The following code shows how to set the value of the <input> field:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("input:text").val("test");
    });//from w ww .  j  av  a  2  s. c  o m
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user"></p>

<button>Set the value of the input field</button>

</body>
</html>

Related Tutorials