温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用JavaScript获取下拉框的value值

发布时间:2022-09-26 14:51:37 来源:亿速云 阅读:498 作者:iii 栏目:开发技术

本文小编为大家详细介绍“如何使用JavaScript获取下拉框的value值”,内容详细,步骤清晰,细节处理妥当,希望这篇“如何使用JavaScript获取下拉框的value值”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

我们可以使用 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值”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI