0

我正在尝试制作一个选择器,它将根据您在另一个选择字段中选择的内容显示选项。它看起来像这样:

           <select name="field2" id="field2" required="required">
                <option id="field2-1" value="os1">
                     os1
                </option>
                <option id="field2-2" value="os2">
                     os2
                </option>
                <option id="field2-3" value="os3">
                     os3
                </option>
           </select>

然后我有第二个选择器,带有这些选项:

           <select name="field3" id="field3" required="required">
                <option id="field3-1" value="dl1">
                     dl1
                </option>
                <option id="field3-2" value="dl2">
                     dl2
                </option>
           </select>

基本上我需要发生的是:如果在第一个选择器中选择了 os1,那么 dl1 和 dl2 都将在第二个选择器中可用。

如果在第一个选择器中选择了 os2 或 os3,则 dl1 将被隐藏,而在第二个选择器中只显示 dl2。

我似乎找不到一个可靠的解决方案,但我不是最擅长 js,所以希望你们中的一个人能指出我正确的方向。

谢谢 :)

4

3 回答 3

1

Vanilla JS 解决方案(无需 jQuery) - DEMO

var selectOne = document.getElementById("field2");

selectOne.addEventListener("change", function() {
    if (this.options[this.selectedIndex].value == 'os2' || this.options[this.selectedIndex].value == 'os3') {
        document.getElementById('field3-2').style.display = "none";
    } else {
        document.getElementById('field3-2').style.display = "block";
    }
}, false);
于 2012-08-16T19:57:42.933 回答
0

有几种方法可以尝试,但最简单的一种可能是隐藏两个“模板”SELECT 元素,然后将这些隐藏的 SELECT 元素中的 html 复制到 #field3 SELECT 元素。在这个例子中,我假设你没有使用 jQuery。

例如:

<SELECT id="template_1">
            <option id="field3-1" value="dl1">
                 dl1
            </option>
            <option id="field3-2" value="dl2">
                 dl2
            </option>
</SELECT>
<SELECT id="template_2">
            <option id="field3-1" value="dl1">
                 dl1
            </option>
            <option id="field3-2" value="dl2">
                 dl2
            </option>
</SELECT>

那么你的javascript将是:

var field2 = document.getElementById('field2');
var field3 = document.getElementById('field3');
var template1 = document.getElementById('template_1');
var template2 = document.getElementById('template_2');
var os = field2.options[field2.selectedIndex];
if (os == 'os1') {
    field3.innerHTML = template1.innerHTML;
}
else {
    field3.innerHTML = template2.innerHTML;
}
于 2012-08-16T19:51:49.770 回答
0

编辑:对不起,没有意识到缺少jquery标签。好吧,如果您想使用 jQuery,下面的代码将起作用:

$('#field2').change(function(){
    if($(this).val() === 'os2' || $(this).val() === 'os3'){
        $('#field3-1').hide();
    }
    else{
        $('#field3-1').show();
    }
});
于 2012-08-16T19:51:51.290 回答