Javascript jQuery显示/隐藏选项从一个选择下拉,当其他选择下拉列表上的选项时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7697936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:13:20  来源:igfitidea点击:

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

javascriptjquery

提问by Nick

I need to show/hide options on one select drop down dependant on another select drop down options.

我需要根据另一个选择下拉选项在一个选择下拉列表中显示/隐藏选项。

The code below shows what I am trying to achieve.

下面的代码显示了我想要实现的目标。

If the 'column_select' select menu option is set to '1 column' then the 'layout_select' select menu must display only the 'none' option.

如果“column_select”选择菜单选项设置为“1 column”,则“layout_select”选择菜单必须仅显示“none”选项。

If the 'column_select' select menu option is set to '2 column' then the 'layout_select' select menu must display only the 'layout 1' and 'layout 2' options.

如果“column_select”选择菜单选项设置为“2 column”,则“layout_select”选择菜单必须仅显示“layout 1”和“layout 2”选项。

If the 'column_select' select menu option is set to '3 column' then the 'layout_select' select menu must display only the 'layout 3', 'layout 4' and 'layout 5' options.

如果“column_select”选择菜单选项设置为“3 column”,则“layout_select”选择菜单必须仅显示“layout 3”、“layout 4”和“layout 5”选项。

<select name="column_select" id="column_select">
    <option value="col1">1 column</option>
    <option value="col2">2 column</option>
    <option value="col3">3 column</option>
</select>

<select name="layout_select" id="layout_select">
    <!--Below shows when '1 column' is selected is hidden otherwise-->
    <option value="col1">none</option>

    <!--Below shows when '2 column' is selected is hidden otherwise-->
    <option value="col2_ms">layout 1</option> 
    <option value="col2_sm">layout 2</option>

    <!--Below shows when '3 column' is selected is hidden otherwise-->
    <option value="col3_mss">layout 3</option>
    <option value="col3_ssm">layout 4</option>
    <option value="col3_sms">layout 5</option>
</select>

So far everything I have tried has failed abysmally.... I am new to jQuery. If anybody could please help it would be much appreciated. Thanks!

到目前为止,我尝试过的一切都失败了……我是 jQuery 新手。如果有人可以请帮助,将不胜感激。谢谢!

回答by ipr101

Try -

尝试 -

$("#column_select").change(function () {
    $("#layout_select").children('option').hide();
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})  

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

如果您打算使用此解决方案,则需要在 document.ready 函数中隐藏除具有“none”值的元素之外的所有元素 -

$(document).ready(function() {
    $("#layout_select").children('option:gt(0)').hide();
    $("#column_select").change(function() {
        $("#layout_select").children('option').hide();
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
    })
})

Demo - http://jsfiddle.net/Mxkfr/2

演示 - http://jsfiddle.net/Mxkfr/2

EDIT

编辑

I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

我可能对此有点不知所措,但这里有一个进一步的例子,它使用原始选择列表选项的缓存来确保“layout_select”列表在“ column_select' 列表已更改 -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"
        }
    })

    $("#column_select").change(function() {
        $("#layout_select").children('option').remove();
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {
                addoptarr.push(optarray[i].option);
            }
        }
        $("#layout_select").html(addoptarr.join(''))
    }).change();
})

Demo - http://jsfiddle.net/N7Xpb/1/

演示 - http://jsfiddle.net/N7Xpb/1/

回答by Andrew Whitaker

How about:

怎么样:

(Updated)

更新

$("#column_select").change(function () {
    $("#layout_select")
        .find("option")
        .show()
        .not("option[value*='" + this.value + "']").hide();

    $("#layout_select").val(
        $("#layout_select").find("option:visible:first").val());

}).change();

(assuming the third optionshould have a value col3)

(假设第三个option应该有一个值col3

Example:http://jsfiddle.net/cL2tt/

示例:http : //jsfiddle.net/cL2tt/

Notes:

笔记:

  • Use the .change()event to define an event handler that executes when the value of select#column_selectchanges.
  • .show()all options in the second select.
  • .hide()all options in the second selectwhose valuedoes not contain the valueof the selected option in select#column_select, using the attribute contains selector.
  • 使用.change()事件来定义在值select#column_select更改时执行的事件处理程序。
  • .show()所有options 在第二个select
  • .hide()option第二个中select的所有svalue不包含value中所选选项的select#column_select,使用属性 contains selector

回答by RitchieD

And in 2016.....I do this (which works in all browsers and does not create "illegal" html).

而在 2016 年......我这样做了(它适用于所有浏览器并且不会创建“非法”html)。

For the drop-down select that is to show/hide different values add that value as a data attribute.

对于显示/隐藏不同值的下拉选择,将该值添加为数据属性。

<select id="animal">
    <option value="1" selected="selected">Dog</option>
    <option value="2">Cat</option>
</select>
<select id="name">
    <option value=""></option>
    <option value="1" data-attribute="1">Rover</option>
    <option value="2" selected="selected" data-attribute="1">Lassie</option>
    <option value="3" data-attribute="1">Spot</option>
    <option value="4" data-attribute="2">Tiger</option>
    <option value="5" data-attribute="2">Fluffy</option>
</select>

Then in your jQuery add a change event to the first drop-down select to filter the second drop-down.

然后在您的 jQuery 中将更改事件添加到第一个下拉列表选择以过滤第二个下拉列表。

$("#animal").change( function() {
    filterSelectOptions($("#name"), "data-attribute", $(this).val());
});

And the magic part is this little jQuery utility.

神奇的部分是这个小小的 jQuery 实用程序。

function filterSelectOptions(selectElement, attributeName, attributeValue) {
    if (selectElement.data("currentFilter") != attributeValue) {
        selectElement.data("currentFilter", attributeValue);
        var originalHTML = selectElement.data("originalHTML");
        if (originalHTML)
            selectElement.html(originalHTML)
        else {
            var clone = selectElement.clone();
            clone.children("option[selected]").removeAttr("selected");
            selectElement.data("originalHTML", clone.html());
        }
        if (attributeValue) {
            selectElement.children("option:not([" + attributeName + "='" + attributeValue + "'],:not([" + attributeName + "]))").remove();
        }
    }
}

This little gem tracks the current filter, if different it restores the original select (all items) and then removes the filtered items. If the filter item is empty we see all items.

这个小宝石跟踪当前过滤器,如果不同,它会恢复原始选择(所有项目),然后删除过滤后的项目。如果过滤器项目为空,我们会看到所有项目。

回答by Bharat Parmar

Initialy both dropdown have same option ,the option you select in firstdropdown is hidden in seconddropdown."value" is custom attribute which is unique.

最初两个下拉菜单都有相同的选项,您在 firstdropdown 中选择的选项隐藏在 seconddropdown 中。“value”是唯一的自定义属性。

$(".seconddropdown option" ).each(function() {
    if(($(this).attr('value')==$(".firstdropdown  option:selected").attr('value') )){
        $(this).hide();
        $(this).siblings().show();
    }
});

回答by Jouke

A litle late perhaps but I would suggest

也许晚了一点,但我建议

$(document).ready(function() {
    var layout_select_html = $('#layout_select').html(); //save original dropdown list

    $("#column_select").change(function () {
        var cur_column_val = $(this).val(); //save the selected value of the first dropdown
        $('#layout_select').html(layout_select_html); //set original dropdown list back
        $('#layout_select').children('option').each(function(){ //loop through options
        if($(this).val().indexOf(cur_column_val)== -1){ //do your conditional and if it should not be in the dropdown list
           $(this).remove(); //remove option from list
        }
    });
});

回答by rodneyrehm

// find the first select and bind a click handler
$('#column_select').bind('click', function(){
    // retrieve the selected value
    var value = $(this).val(),
        // build a regular expression that does a head-match
        expression = new RegExp('^' + value),
        // find the second select
        $select = $('#layout_select);

    // hide all children (<option>s) of the second select,
    // check each element's value agains the regular expression built from the first select's value
    // show elements that match the expression
    $select.children().hide().filter(function(){
      return !!$(this).val().match(expression);
    }).show();
});

(this is far from perfect, but should get you there…)

(这远非完美,但应该能让你到达那里......)