There is a val() method in JavaScript. This method can return the value attribute value of the first matching element, or set the value attribute value of all matching elements. The syntax is "$(selector).val() ” or “$(selector).val(value)”.

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
Does JavaScript have a val method?
The val() method returns or sets the value attribute of the selected element.
When used to return a value:
This method returns the value of the value attribute of the first matching element.
When used to set a value:
This method sets the value of the value attribute of all matching elements.
Note: The val() method is typically used with HTML form elements.
Syntax
Return value attribute:
$(selector).val()
Set value attribute:
$(selector).val(value)
Set value attribute through function:
$(selector).val(function(index,currentvalue))
The example is as follows :
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:text").val("設(shè)置輸入字段的值");
});
});
</script>
</head>
<body>
<p>名稱: <input type="text" name="user"></p>
<button>設(shè)置輸入字段的值</button>
</body>
</html>
Output result:

After clicking the button:

Related recommendations :javascript learning tutorial
The above is the detailed content of Does JavaScript have a val method?. For more information, please follow other related articles on the PHP Chinese website!