jQuery Learning-Style (6): jQuery Gets and Sets the Value of Form Elements

Link to the original text of this article: https://blog.csdn.net/xzk9381/article/details/111985447

In jQuery, you can use the val() method to process the value of form elements, such as input, select, and textarea:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$(document).ready(function (){
     
     
			// 获取和设置 input 中的 value
			console.log($('#myinput').val());
			$('#myinput').val("input测试完成");

			// 获取和设置 textarea 中的 value
			console.log($('#mytextarea').val());
			$('#mytextarea').val("textarea 测试完成");

			// 只能用来获取 select 中的 value,不能修改。获取到的 value 是当前被选中的 option 对应的 value
			console.log($('#myselect').val());
		})
	</script>
</head>
<body>
	<input type="button" value="input测试" id="myinput">
	<textarea id="mytextarea">textarea 测试</textarea>
	<select id="myselect">
		<option>选择1</option>
		<option>选择2</option>
		<option selected="selected">选择3</option>
		<option>选择4</option>
	</select>
</body>
</html>

In fact, for input and textarea, using jQuery to get the value has no particular advantage over the native method. Especially for textarea, in addition to using the val() method, you can also use the html() and text() methods to get and modify the value.

The most obvious advantage is the modification of the select tag. For example, in the above code, if you use the native method to get the currently selected option value, you need to use the following method:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		onload = function (){
     
     
			var index = myselect.selectedIndex;
			console.log(index);
			console.log(myselect.options[index].text)
		}
	</script>
</head>
<body>
	<select id="myselect">
		<option>选择1</option>
		<option>选择2</option>
		<option selected="selected">选择3</option>
		<option>选择4</option>
	</select>
</body>
</html>

Using jQuery can reduce a lot of code.

Another thing to note is that if there are multiple identical elements in the code, when using the val() method, only the first value that matches the element will be obtained:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$(document).ready(function (){
     
     
			console.log($('input').val())
		})
	</script>
</head>
<body>
	<input type="button" value="input测试1" id="myinput">
	<input type="button" value="input测试2" id="myinput">
	<input type="button" value="input测试3" id="myinput">
</body>
</html>

If it is a select tag, it will only match the first selected option in the first select tag.

Link to the original text of this article: https://blog.csdn.net/xzk9381/article/details/111985447

Guess you like

Origin blog.csdn.net/xzk9381/article/details/111985447