根据另一个选择更新选择菜单

Update Select Menu based off another Selection

本文关键字:选择 更新 菜单 另一个      更新时间:2023-09-26

我有一个州(美国)列表,其中包括加拿大各省,

<select>
<optgroup label="United States">
    <option value="AL">Alabama (AL)</option><option value="AK">Alaska (AK)</option><option value="AE">APO state (AE)</option><option value="AO">APO state (AO)</option><option value="AP">APO state (AP)</option><option value="AZ">Arizona (AZ)</option>
</optgroup>
<optgroup label="Canada">
<option value="AB">Alberta (AB)</option><option value="BC">British Columbia (BC)</option><option value="MB">Manitoba (MB)</option><option value="NB">New Brunswick (NB)</option><option value="NL">Newfoundland and Labrador (NL)</option></optgroup>
</select>

然后我有另一个选择菜单,其中包括2个选项,美国和;加拿大。(默认选择美国)

我想如果加拿大省被选中,禁用美国作为国家在第二个选择菜单。如果在第二个选择菜单中选择了加拿大,则从第一选择菜单中删除美国各州。

我只找到了在选择第一个选择菜单后填充第二个选择菜单的方法(如http://jsfiddle.net/FK7ga/),但我尝试的是在默认情况下显示所有选择菜单,并在选择任何一个后更新。

你可以这样做:

$("#filter").on("change", function() {
    $states = $("#states");
    $states.find("optgroup").hide().children().hide();
    $states.find("optgroup[label='" + this.value + "']").show().children().show();
    $states.find("optgroup[label='" + this.value + "'] option").eq(0).prop("selected", true);
});

查看此工作演示

@letiagoalves:

我刚刚编辑了你的小提琴,将show/hide更改为attr('disable','disable');removeAttr('disable');,这导致列表保留,但防止错误的状态组被选中。

我的2美分。

在@letiagoalves的帮助下,我能够使它像我想要的那样工作,下面是代码

$("#countries").on("change", function () 
{
    if ($("#countries").find(":selected").val())
    {
        $states = $("#states");
        $states.find("optgroup").hide().children().hide();
        $states.find("optgroup[label='" + this.value + "']").show().children().show();
        $states.find("optgroup[label='" + this.value + "'] option").eq(0).prop("selected", true);
    }
    else
    {
        $states.show().children().show().children().show();
    }
});
$("#states").on("change", function () {
    $countries = $("#countries");
    if ($("#states").find("option:selected")) 
    {
        var c = $("#states").find("option:selected").parent().attr("label");
        $countries.find("option[value='" + c + "']").prop("selected", true);
        $("#countries").change();
    }
});

仍然试图使它与@Alex-Amthor的禁用的想法工作,如果我成功,将更新答案。同时这里有一个关于jsfiddle

的演示