JavaScript 获取下拉列表 Option 的 Value 与 Text 值示例
作者:小括号时间:2026-10-27 21:15:24浏览:341
本文介绍如何在 JavaScript 中获取下拉列表框中 Option 元素的 Value 和 Text 值。通过示例代码展示了如何获取显示在页面上的文本值以及对应的 Value 值,并提供了表单提交时的验证逻辑。
JavaScript 获取下拉列表 Option 的 Value 与 Text 值示例
在开发实践中,处理下拉列表框时通常需提取 option 的 value 属性,但有时也需获取页面展示文本。例如,针对 <option value="value">ShowText</option>,如何提取 "ShowText"?操作简便,实现代码如下:
具体代码实现如下:
<script type="text/javascript">
function a(object){
alert(object);
}
</script>
<!-- 获取显示的值 -->
<select onchange="a(this.options[this.selectedIndex].innerText);">
<option value="value-a">text-a</option>
<option value="value-b">text-b</option>
</select>
<!-- 获取value的值 -->
<select onchange="a(this.options[this.selectedIndex].value);">
<option value="value-c">text-c</option>
<option value="value-d">text-d</option>
</select>
function isSelect(selectPress) {
//var select = document.getElementById("mySelect").ind;
var selectValue = selectPress.options[selectPress.selectedIndex].value; //显示value 下标0、1、2
var selectValue2 = selectPress.options[selectPress.selectedIndex].innerText; //显示显示的值 具体内容(上海、北京)
//alert(selectValue);
//alert(selectValue2);
if (selectValue == "-1") {
alert("请选择城市,表单提交被拒绝!")
return;
}
else {
document.getElementById('form1').submit(); //form表单提交
}
}
<select onchange="isSelect(this);" id="mySelect">
<option value="-1">--请选择--</option>
<option value="0">北京</option>
<option value="1">上海</option>
<option value="2">武汉</option>
</select>作者最新文章
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
