Question

This is the code, I'd like to show a hided input when I select the option "other", but it it doesn't work

    <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';
        }

    }
}

It work when using selectedIndex

if(eSelect.selectedIndex === 3) {

but I'd like to use the value of option

Était-ce utile?

La solution

Just change this:

eSelect.options[selectedIndex].value

to this:

eSelect.options[eSelect.selectedIndex].value

Or as @CoreyRothwell said(and the best/right way):

eSelect.value

You're probably getting(in the console):

selectedIndex is not defined

It worked here.

Autres conseils

change

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

to

eSelect.value == "other"

the value in the option tag is Other but you are comparing it with other you should change it like this:

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';
        }

    }
}

Or just do this:

if (selectedValue.toLowerCase() == "Other") {//replace the "other" with "Other"
    optOtherReason.style.display = 'block';
} else {
    optOtherReason.style.display = 'none';
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top