Home > Web Front-end > Front-end Q&A > How to use jquery val() method

How to use jquery val() method

青灯夜游
Release: 2022-03-01 18:03:56
Original
4898 people have browsed it

In jquery, the val() method can be used to return the value of the value attribute of the first matching element, with the syntax "$(selector).val()"; it can also be used to set the value of all matching elements. The value of the attribute, the syntax is "$(selector).val("new value")".

How to use jquery val() method

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery val() method

In jquery, the val() method is used to return or set the value of 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.

$(selector).val()
Copy after login
  • When used to set a value:

    This method sets the value of the value attribute of all matching elements.

$(selector).val(value)

//通过函数设置 value 属性:
$(selector).val(function(index,currentvalue))
Copy after login

How to use jquery val() method

Example 1: Return the value of the value attribute of the first matching element.

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function(){
				$("button").click(function(){
					alert($("input").val());
				});
			});
		</script>
	</head>
	<body>

		喜欢的水果: <input type="text" name="fname" value="苹果"><br><br>
		<button>返回输入字段的值</button>
	</body>
</html>
Copy after login

How to use jquery val() method

Example 2: Set the value of the field

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function(){
				$("button").click(function(){
					$("input").val("榴莲");
				});
			});
		</script>
	</head>
	<body>

		喜欢的水果: <input type="text" name="fname" value="苹果"><br><br>
		<button>设置输入字段的值</button>
	</body>
</html>
Copy after login

How to use jquery val() method

##[Recommended learning:

jQuery video tutorialweb front-end development video

The above is the detailed content of How to use jquery val() method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template