JS 获取select选中的option选中的值
在前端开发中,有时候我们需要获取用户在下拉框(select)中选择的值,然后根据这个值做出相应的操作。本文将详细介绍如何使用 JavaScript 获取 select 中选中的 option 的值。
HTML代码示例
首先,让我们来看一个简单的 HTML 页面,其中包含一个 select 元素:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select Example</title>
</head>
<body>
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>
<button onclick="getSelectedValue()">Get Selected Value</button>
<p id="selectedValue"></p>
<script src="script.js"></script>
</body>
</html>
在上面的代码中,我们创建了一个包含5个选项的下拉框(select),并且在其后面放置了一个按钮,当点击这个按钮时,将会调用一个 JavaScript 函数来获取 select 元素中选中的值,并将其显示在页面中。
JavaScript代码示例
接着,让我们来看一下 script.js 文件中的代码:
function getSelectedValue() {
var selectElement = document.getElementById("mySelect");
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
document.getElementById("selectedValue").innerText = "Selected value is: " + selectedValue;
}
在上述代码中,我们首先获取了 id 为 mySelect
的 select 元素,然后通过 selectedIndex
属性获取到选中的 option 的索引,最后通过 options
属性获取到所有的 option 元素,并通过选中的索引获取选中的 option 的值。
最后,我们将获取到的选中值显示在页面中,这里我们将其显示在 id 为 selectedValue
的段落元素中。
效果演示
接下来,我们来看一下页面实际运行的效果:
- 当页面加载完成时,页面中将会显示一个下拉框和一个按钮
- 选择下拉框中的某个选项
- 点击按钮,页面会显示出选中的值
利用上述代码,我们就可以在前端中获取用户通过 select 元素选择的值,并进行相应的操作。
总结
通过上面的示例,我们可以看到如何使用 JavaScript 来获取 select 元素中选中的 option 的值。在实际开发中,我们可以根据这个值进行各种不同的操作,比如条件判断、表单提交等等。