原生js获取select标签选中值

时间:2023-02-10 19:34:18
this.selectedIndex; // 选中的索引
this.options[_index].text; // 选中的文本
this.options[_index].value; // 选中的值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js获取select选中值</title>
<style type="text/css">
body{
padding-left: 100px;
}

div{
margin: 10px 0;
}

</style>
</head>
<body>
<select id="one">
<option>11111</option>
<option>22222</option>
<option>33333</option>
</select>
<div class="one"></div>

<select id="two" multiple="true">
<option>11111</option>
<option>22222</option>
<option>33333</option>
</select>
<div class="two"></div>

<script>
/**
* 原生JS获取select选中值
**/

var one = document.getElementById('one');
one.addEventListener('change', function() {
var _index = this.selectedIndex; // 选中索引,如果是多选,则永远获取第一个
var _text = this.options[_index].text; // 选中文本
var _value = this.options[_index].value; // 选中值

document.getElementsByClassName('one')[0].innerText= "选中的索引是:"+_index
+ " 选中的文本是:"+ _text
+ " 选中的值是:" + _value;
})

/**
* 原生JS获取多选select选中值
**/

var two = removeWhitespace(document.getElementById('two'));
two.addEventListener('change', function() {
var _two = document.getElementsByClassName('two')[0];
var str=""; // 存储选中值
var fid = two.childNodes; // 得到所有的option
for(var i = 0; i < fid.length; i++) {
if(fid[i].selected==true){ // 判断
str += "选中索引:"+ fid[i].index + ",选中文本:"+fid[i].text + "选中值:" + fid[i].value +",";

}

}
_two.innerText = str;
})

// 清除节点内空格
function removeWhitespace(xml){
var loopIndex;

for (loopIndex = 0; loopIndex < xml.childNodes.length; loopIndex++){
var currentNode = xml.childNodes[loopIndex];
if (currentNode.nodeType == 1){
removeWhitespace(currentNode);
}

if (((/^\s+$/.test(currentNode.nodeValue))) &&(currentNode.nodeType == 3)){
xml.removeChild(xml.childNodes[loopIndex--]);
}
}
return xml;
}
</script>
</body>

</html>