更新根据其他选择选择菜单

时间:2013-05-29 16:14:11

标签: javascript jquery

我有一份州(美国)名单,其中包括加拿大各省,

<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个选项,USA&amp;加拿大。 (默认选择美国)

我希望如果选择加拿大省,请在第二个选择菜单中禁用USA作为国家/地区。如果在第二个选择菜单中选择加拿大,则从第一个选择菜单中删除美国州。

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

3 个答案:

答案 0 :(得分:1)

您可以这样做:

$("#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);
});

<强> See this working DEMO

答案 1 :(得分:1)

@letiagoalves:

我刚刚编辑了你的小提琴,将show/hide更改为attr('disable','disable');removeAttr('disable');这会导致列表停留,但会阻止错误的州群被选中。

只需2美分。

答案 2 :(得分:1)

@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's idea禁用,如果成功,将更新答案。同时这里是demo on jsfiddle

相关问题