jQuery val()

Introduction

Set the value of the <input> field:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//from   www  . j  ava  2s.  c om
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("input:text").val("new value");
  });
});
</script>
</head>
<body>

<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>

</body>
</html>

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

As getter, this method returns the value of the value attribute of the first matched element.

As setter, this method sets the value of the value attribute for all matched elements.

Return the value attribute:

$(selector).val()

Set the value attribute:

$(selector).val(value)

Set the value attribute using a function:

$(selector).val(function(index,current_value))
Parameter
Optional
Description
value
Required.
the value of the value attribute
function(index,current_value)


Optional.


sets a function that returns the value to set.
index - the index position of the element in the set
current_value - the current value attribute of selected elements



PreviousNext

Related