【问题标题】:Hide/Show <select> depending on the other <select>隐藏/显示 <select> 取决于其他 <select>
【发布时间】:2011-03-20 20:22:39
【问题描述】:

我有两个 &lt;select&gt; 元素。第一个包含国家/地区(例如美国、加拿大、英国、俄罗斯、波兰...),第二个是隐藏的,包含美国和加拿大的城市(例如纽约、洛杉矶、芝加哥) ...或者渥太华、温哥华、萨里...)

如果用户从第一个&lt;select&gt; 中选择加拿大或美国,则第二个应显示和 让他选择他的城市。

有可能吗?我访问了很多带有 Ajax 和 JQuery 验证表单的网站,但没有找到类似的来源。

谢谢。

【问题讨论】:

    标签: javascript jquery html ajax forms


    【解决方案1】:

    真的很简单。
    首先准备change 事件处理程序http://api.jquery.com/change/
    其次,检查您选择的val 的值:http://api.jquery.com/val/
    第三,显示或隐藏你的第二个selecthttp://api.jquery.com/hide/http://api.jquery.com/show/

    【讨论】:

      【解决方案2】:

      监听选择列表的更改事件。在更改事件中,如果选择的值为“美国”或“加拿大”,则显示另一个选择列表,否则隐藏它。

      查看example

      假设选择结构如下所示:

      <select id="countries">
          <option val="USA">USA</option>
          <option val="Canada">Canada</option>
          <option val="Australia">Australia</option>
          ...
      </select>
      
      <select id="cities">
          <option val="Vancouver">Vancouver</option>
          <option val="New York">New York</option>
          ...
      </select>
      

      收听国家数组上的更改事件。

      $("#countries").change(function() {
          // find the selected country
          var selectedCountry = $(this).val();
          // if US or Canada
          if(selectedCountry == "USA" || selectedCountry == "Canada") {
              // show the cities list
              $("#cities").show();
          }
          // otherwise hide it
          else {
              $("#cities").hide();
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        • 2011-05-16
        • 2020-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多