【问题标题】:Update Select Menu based off another Selection根据另一个选择更新选择菜单
【发布时间】:2013-05-25 00:23:40
【问题描述】:

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

<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/),但我尝试的是默认显示全部,并在选择任何一个后更新。

【问题讨论】:

标签: javascript jquery


【解决方案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

【讨论】:

    【解决方案2】:

    @letiagoalve:

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

    只要我的 2 美分。

    【讨论】:

      【解决方案3】:

      @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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-12
        • 1970-01-01
        • 2012-10-31
        • 1970-01-01
        • 1970-01-01
        • 2022-01-06
        相关资源
        最近更新 更多