1. 程式人生 > >原生js獲取select標籤選中值

原生js獲取select標籤選中值

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>