用于获取select选项值的javascript代码

javascript code for getting the select option value

本文关键字:javascript 代码 选项 获取 select 用于      更新时间:2023-09-26

我正在使用代码来检测选择框的所选选项的值,我正在使用下面的代码和firefox,它工作得很好,但在chrome和IE上,它抛出了一个错误。由于项目限制,我不能在这里使用jquery:

var regID= document.getElementById("tdd");
            if (regID != null || regID != 'undefined' || regID != undefined) {
                var passvalue = regID.options[regID.selectedIndex].value;
}
Error by Chrome: Uncaught TypeError: Cannot read property 'value' of undefined 

Firefox没有抛出任何错误

看看<select>:的value

jsfiddle:http://jsfiddle.net/7kr6x7uh/更新了fiddle并添加了检查,以查看您的<select>是否为空:http://jsfiddle.net/7kr6x7uh/1/

html:

<select id="tdd">
    <option val="1">Option 1</option>
    <option val="2">Option 2</option>
    <option val="3" selected="selected">Option 3</option>
</select>

javascript:

var select = document.getElementById('tdd');
if (select){
    alert(tdd.value); //  in your case, do 'var passvalue = tdd.value;'
}