Onchange选择选项

时间:2014-01-28 17:21:02

标签: javascript onchange

这是代码,我想在选择“其他”选项时显示隐藏输入,但它不起作用

    <select id="transfer_reason" name="transfer_reason">
    <option value="text">Text</option>
    <option value="email">Email</option>
    <option value="integer">Integer</option>
    <option value="other">Other</option>
</select>
<input type="text" id="otherdetail" value="" style="display: none;"  />



<script type="text/javascript">
window.onload = function() {
    var eSelect = document.getElementById('transfer_reason');
    var optOtherReason = document.getElementById('otherdetail');


    eSelect.onchange = function() {
        if(eSelect.options[selectedIndex].value == "other") {
            optOtherReason.style.display = 'block';
        }
         else {
            optOtherReason.style.display = 'none';
        }

    }
}

使用selectedIndex

时有效
if(eSelect.selectedIndex === 3) {

但我想使用选项

的值

3 个答案:

答案 0 :(得分:2)

只需改变一下:

eSelect.options[selectedIndex].value

到此:

eSelect.options[eSelect.selectedIndex].value

或者@CoreyRothwell说(以及最佳/正确的方式):

eSelect.value

你可能正在(在控制台中):

  

selectedIndex未定义

它有效here

答案 1 :(得分:1)

更改

eSelect.options[selectedIndex].value == "other"

eSelect.value == "other"

答案 2 :(得分:0)

选项标记中的值为Other,但您要将其与other进行比较,您应该将其更改为:

window.onload = function () {
    var eSelect = document.getElementById('transfer_reason');
    var optOtherReason = document.getElementById('otherdetail');


    eSelect.onchange = function () {
        var selectedValue = eSelect.options[eSelect.selectedIndex].value;
        //OR
        selectedValue = eSelect.value;

        //BUT the important point is using toLowerCase() like this
        if (selectedValue.toLowerCase() == "other") {
            optOtherReason.style.display = 'block';
        } else {
            optOtherReason.style.display = 'none';
        }

    }
}

或者只是这样做:

if (selectedValue.toLowerCase() == "Other") {//replace the "other" with "Other"
    optOtherReason.style.display = 'block';
} else {
    optOtherReason.style.display = 'none';
}