Definition and Usage
The val() method returns or sets the value attribute of the selected elements.
When used to return value:
This method returns the value of the value attribute of the FIRST matched element.
When used to set value:
This method sets the value of the value attribute for ALL matched elements.
输出结果只有一个:
输出结果:
The val() method returns or sets the value attribute of the selected elements.
When used to return value:
This method returns the value of the value attribute of the FIRST matched element.
When used to set value:
This method sets the value of the value attribute for ALL matched elements.
Note: The val() method is mostly used with HTML form elements.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("input:text").val());
});
});
</script>
</head>
<body>
Firstname: <input type="text" name="fname" value="Peter"><br>
Lastname: <input type="text" name="lname" value="Griffin"><br><br>
<button>Return the value of the first input field</button>
</body>
</html>
输出结果只有一个:
Peter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:text").val("Glenn Quagmire");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<p>Name2: <input type="text" name="user2"></p>
<button>Set the value of the input field</button>
</body>
</html>
输出结果:
两个框框都设置成了相同的值