专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 使用JavaScript获取下拉框的value值

使用JavaScript获取下拉框的value值

更新时间:2022-09-09 09:44:26 来源:赢咖4 浏览977次

大家在Java赢咖4在线学习技术文档中会学到很多知识,在本文中,我们将学习在 Javascript 中获取下拉列表中的选定值。我们可以使用 2 种方法获取值:

1.通过使用 value 属性

2.通过将 selectedIndex 属性与 option 属性一起使用

我们将通过示例了解这两种方法。

方法 1:使用value 属性:

可以使用定义列表的选定元素上的 value 属性找到选定元素的值。此属性返回一个字符串,表示列表中<option>元素的 value 属性。如果未选择任何选项,则不会返回任何内容。

句法:

选择元素值

示例:此示例描述了可以为选定元素找到的 value 属性。

<!DOCTYPE html>
<head>
	<title>
		How to get selected value in
		dropdown list using JavaScript?
	</title>
</head>
<body>
	<h1 style="color: green">
		GeeksforGeeks
	</h1>
	<b>
		How to get selected value in dropdown
		list using JavaScript?
	</b>	
<p> Select one from the given options:
		<select id="select1">
			<option value="free">Free</option>
			<option value="basic">Basic</option>
			<option value="premium">Premium</option>
		</select>
	</p>	
<p> The value of the option selected is:
		<span class="output"></span>
	</p>
	<button onclick="getOption()"> Check option </button>	
	<script type="text/javascript">
	function getOption() {
		selectElement = document.querySelector('#select1');
		output = selectElement.value;
		document.querySelector('.output').textContent = output;
	}
	</script>
</body>
</html>

输出:

方法 2:将selectedIndex 属性与option 属性一起使用:

selectedIndex 属性返回下拉列表中当前选定元素的索引。此索引从 0 开始,如果未选择任何选项,则返回 -1。options 属性返回<select> 下拉列表中所有选项元素的集合。元素根据页面的源代码进行排序。在它之前找到的索引可以和这个属性一起使用来获取被选中的元素。可以使用 value 属性找到此选项的值。

句法:

selectElement.options[selectElement.selectedIndex].value

适当的价值:

selectedIndex:用于设置或获取集合中选中的<option>元素的索引。

length:它是只读属性,用于获取集合中<option>元素的数量。

返回值:通过指定<select>元素中的所有<option>元素返回 HTMLOptionsCollection 对象。该元素将在集合中排序

示例:此示例描述了 selectedIndex 属性和 option 属性。

<!DOCTYPE html>
<head>
	<title>
		How to get selected value in
		dropdown list using JavaScript?
	</title>
</head>
<body>
	<h1 style="color: green">
		GeeksforGeeks
	</h1>
	<b>
		How to get selected value in
		dropdown list using JavaScript?
	</b>	
<p> Select one from the given options:
		<select id="select1">
			<option value="free">Free</option>
			<option value="basic">Basic</option>
			<option value="premium">Premium</option>
		</select>
	</p>	
<p> The value of the option selected is:
		<span class="output"></span>
	</p>
	<button onclick="getOption()">Check option</button>
	<script type="text/javascript">
	function getOption() {
		selectElement = document.querySelector('#select1');
		output = selectElement.options[selectElement.selectedIndex].value;
		document.querySelector('.output').textContent = output;
	}
	</script>
</body>
</html>

输出:

以上就是关于“使用JavaScript获取下拉框的value值”的介绍,大家如果对此比较感兴趣,不妨来关注一下赢咖4的JavaScript教程,里面还有更丰富的知识等着大家去学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>