使用开关显示特定的下拉菜单选项

时间:2014-10-15 18:06:09

标签: javascript html switch-statement

Javascript的新手,我正在尝试创建一个简单的switch语句来显示和隐藏下拉菜单中的特定选项。不确定我做错了什么。所有帮助表示赞赏。感谢

function showHall() {
    var x = document.getElementById("schoolName").value;

    switch (x) {
        case "williams_college":
            document.getElementById("williamsHall").style.display = "block";
            document.getElementById("albanyHall").style.display = "none";
            break;
        case "suny_albany":
            document.getElementById("albanyHall").style.display = "block";
            document.getElementById("williamsHall").style.display = "none";
            break;

        default:
            document.getElementById("albanyHall").style.display = "none";
            document.getElementById("williamsHall").style.display = "none";
            break;
    }
}
<tr>
    <th>Select School:</th>
    <td>
        <select id="schoolName" colspan="2" onchange="showHall()">
            <option value="select_school" selected="selected">Select Your School</option>
            <option value="suny_albany">SUNY ALBANY</option>
            <option value="williams_college">WILLIAMS COLLEGE</option>
        </select>
    </td>
</tr>
<tr>
    <th>Hall:</th>
    <td>
        <select id="williamsHall" colspan="2">
            <option selected value="select_school">Select Your Hall</option>
            <option value="AGARD">AGARD</option>
            <option value="ARMSTRONG">ARMSTRONG</option>
            <option class="optionHall" value="OTHER">OTHER</option>
            <option class="optionHall" value="HALL NOT ASSIGNED">HALL NOT ASSIGNED</option>
        <select id="albanyHall" colspan="2">
            <option selected value="select_school">Select Your Hall</option>
            <option value="HALL1">ALBANY HALL1</option>
            <option value="HALL2">ALBANY HALL2</option>
            <option value="HALL3">ALBANY HALL3</option>
            <option value="OTHER">OTHER</option>
            <option value="HALL NOT ASSIGNED">HALL NOT ASSIGNED</option>
            </select>
    </td>
</tr>

2 个答案:

答案 0 :(得分:0)

改变这个:

var x = document.getElementById("schoolName").value;

到此:

var x = document.getElementById("schoolName");
var val = x.options[x.selectedIndex].value;

<强>解释

没有什么特别的,只是缺乏对JS的了解。 .value属性不用于获取下拉列表的选定值,而是为我们提供了一个数组(.options)和一个.selectedIndex,它们共同使我们有机会使用{{1间接地在选定的.value

答案 1 :(得分:0)

JSFiddle在这个小提琴中处理你的JavaScript的方式有点奇怪。我将您的JavaScript移动到HTML上方的脚本标记中,似乎可以正常工作。我还将select元素设置为内联而不是块(它们是内联元素)。似乎工作正常,我认为穆罕默德走在正确的轨道上。看看这个。

http://jsfiddle.net/seano666/2jufk40L/

document.getElementById("williamsHall").style.display = "inline";