【问题标题】:Use jQuery to change a second select list based on the first select list option使用 jQuery 根据第一个选择列表选项更改第二个选择列表
【发布时间】:2012-05-21 04:53:38
【问题描述】:

我有两个选择:

<select name="select1" id="select1">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

<select name="select2" id="select2">
    <option value="1">Banana</option>
    <option value="1">Apple</option>
    <option value="1">Orange</option>
    <option value="2">Wolf</option>
    <option value="2">Fox</option>
    <option value="2">Bear</option>
    <option value="3">Eagle</option>
    <option value="3">Hawk</option>
    <option value="4">BWM<option>
</select>

如果我在第一个选择中选择 Fruit,我如何使用 jQuery 做到这一点?第二个选择只会显示水果 - 香蕉、苹果、橙子。如果我在第一个选择中选择鸟,第二个选择将只显示鸟类 - 鹰、鹰。等等……

我试着用这段 jQuery 代码来做:

$("#select1").change(function() {
    var id = $(this).val();
    $('#select2 option[value!='+id+']').remove();
});

不幸的是,它几乎删除了所有内容,我不知道如何恢复一些选项。我也读过一些关于克隆的东西,但我不知道在这种情况下如何使用它。

【问题讨论】:

  • stackoverflow.com/questions/10200498/… 这可能会帮助您解决问题
  • @santo,不幸的是 hide 仅适用于 Firefox。
  • @Randy 再看一遍我确实有一个问题;当您提交表单时,您将如何传递select2 的选定值?价值观不是唯一的,那么 Banana 与 Apple 的区别是什么?
  • @Jack,这只是一个例子。我还为所有选择选项添加了唯一名称。
  • @Randy 好的,这是您的特权,提交表单时只是额外的工作:)

标签: jquery html select


【解决方案1】:

在选定的答案上,我看到最初加载页面时,第一个选项的选择是预先固定的,因此提供了选择 2 中所有类别的选项。 您可以通过在两个选择标签中添加如下第一个选项来避免这种情况:- &lt;option value="none" selected disabled hidden&gt;Select an Option&lt;/option&gt;

<select name="select1" id="select1">
<option value="none" selected disabled hidden>Select an Option</option>
<option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>


<select name="select2" id="select2">
<option value="none" selected disabled hidden>Select an Option</option>
  <option value="1">Banana</option>
  <option value="1">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Wolf</option>
  <option value="2">Fox</option>
  <option value="2">Bear</option>
  <option value="3">Eagle</option>
  <option value="3">Hawk</option>
  <option value="4">BWM<option>
</select>

【讨论】:

    【解决方案2】:

    尝试使用它:

    下拉框取决于在另一个下拉框中选择的选项。使用 jQuery 根据第一个选择列表选项更改第二个选择列表。

    <asp:HiddenField ID="hdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
    <asp:TextBox ID="txtOfferId" CssClass="hidden" ClientIDMode="Static" runat="server" Text="0" />
    <asp:HiddenField ID="SelectedhdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
    <asp:HiddenField ID="SelectedhdfOfferId" ClientIDMode="Static" runat="server" Value="0" />
    
    <div class="col-lg-2 col-md-2 col-sm-12">
        <span>Service</span>
        <asp:DropDownList ID="ddlService" ClientIDMode="Static" runat="server" CssClass="form-control">
        </asp:DropDownList>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-12">
        <span>Offer</span>
        <asp:DropDownList ID="ddlOffer" ClientIDMode="Static" runat="server" CssClass="form-control">
        </asp:DropDownList>
    </div>
    

    在您的网页中使用 jQuery 库。

    <script type="text/javascript">
        $(document).ready(function () {
            ucBindOfferByService();
            $("#ddlOffer").val($('#txtOfferId').val());
        });
    
        $('#ddlOffer').on('change', function () {
            $("#txtOfferId").val($('#ddlOffer').val());
        });
    
        $('#ddlService').on('change', function () {
            $("#SelectedhdfOfferId").val("0");
            SetServiceIds();
            var SelectedServiceId = $('#ddlService').val();
            $("#SelectedhdfServiceId").val(SelectedServiceId);
            if (SelectedServiceId == '0') {
            }
            ucBindOfferByService();
            SetOfferIds();
        });
    
        function ucBindOfferByService() {
            GetVendorOffer();
            var SelectedServiceId = $('#ddlService').val();
            if (SelectedServiceId == '0') {
                $("#ddlOffer").empty();
                $("#ddlOffer").append($("<option></option>").val("0").html("All"));
            }
            else {
                $("#ddlOffer").empty();
                $(document.ucVendorServiceList).each(function () {
                    if ($("#ddlOffer").html().length == "0") {
                        $("#ddlOffer").append($("<option></option>").val("0").html("All"));
                    }
                    $("#ddlOffer").append($("<option></option>").val(this.OfferId).html(this.OfferName));
                });
            }
        }
    
        function GetVendorOffer() {
            var param = JSON.stringify({ UserId: $('#hdfUserId').val(), ServiceId: $('#ddlService').val() });
            AjaxCall("DemoPage.aspx", "GetOfferList", param, OnGetOfferList, AjaxCallError);
        }
    
        function OnGetOfferList(response) {
            if (response.d.length > 0)
                document.ucVendorServiceList = JSON.parse(response.d);
        }
    
        function SetServiceIds() {
            var SelectedServiceId = $('#ddlService').val();
            var ServiceIdCSV = ',';
            if (SelectedServiceId == '0') {
                $('#ddlService > option').each(function () {
    
                    ServiceIdCSV += $(this).val() + ',';
                });
            }
            else {
                ServiceIdCSV += SelectedServiceId + ',';
            }
            $("#hdfServiceId").val(ServiceIdCSV);
        }
    
        function SetOfferIds() {
            var SelectedServiceId = $('#ddlService').val();
            var OfferIdCSV = ',';
            if (SelectedServiceId == '0') {
                $(document.ucVendorServiceList).each(function () {
                    OfferIdCSV += this.OfferId + ',';
                });
            }
            else {
                var SelectedOfferId = $('#ddlOffer').val();
                if (SelectedOfferId == "0") {
                    $('#ddlOffer > option').each(function () {
                        OfferIdCSV += $(this).val() + ',';
                    });
                }
                else {
                    OfferIdCSV += SelectedOfferId + ',';
                }
            }
        }
    </script>
    

    在您的网页中使用后端代码。

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ServiceList();
        }
    }
    
    public void ServiceList()
    {
        ManageReport manageReport = new ManageReport();
        DataTable ServiceList = new DataTable();
        ServiceList = manageReport.GetServiceList();
        ddlService.DataSource = ServiceList;
        ddlService.DataTextField = "serviceName";
        ddlService.DataValueField = "serviceId";
        ddlService.DataBind();
        ddlService.Items.Insert(0, new ListItem("All", "0"));
    }
    
    public DataTable GetServiceList()
    {
        SqlParameter[] PM = new SqlParameter[]
        {
            new SqlParameter("@Mode"    ,"Mode_Name"    ),
            new SqlParameter("@UserID"  ,UserId         )
        };
        return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", PM).Tables[0];
    }
    
    [WebMethod]
    public static String GetOfferList(int UserId, String ServiceId)
    {
        var sOfferList = "";
        try
        {
            CommonUtility utility = new CommonUtility();
            ManageReport manageReport = new ManageReport();
            manageReport.UserId = UserId;
            manageReport.ServiceId = ServiceId;
            DataSet dsOfferList = manageReport.GetOfferList();
            if (utility.ValidateDataSet(dsOfferList))
            {
                //DataRow dr = dsEmployerUserDepartment.Tables[0].NewRow();
                //dr[0] = "0";
                // dr[1] = "All";
                //dsEmployerUserDepartment.Tables[0].Rows.InsertAt(dr, 0);
                sOfferList = utility.ConvertToJSON(dsOfferList.Tables[0]);
            }
            return sOfferList;
        }
        catch (Exception ex)
        {
            return "Error Message: " + ex.Message;
        }
    }
    
    public DataSet GetOfferList()
    {
        SqlParameter[] sqlParameter = new SqlParameter[]
            {                                                                     
                new SqlParameter("@Mode"        ,"Mode_Name"    ),
                new SqlParameter("@UserID"      ,UserId         ),
                new SqlParameter("@ServiceId"   ,ServiceId      )
            };
        return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", sqlParameter);
    }
    

    【讨论】:

      【解决方案3】:

      $("#select1").change(function() {
        if ($(this).data('options') === undefined) {
          /*Taking an array of all options-2 and kind of embedding it on the select1*/
          $(this).data('options', $('#select2 option').clone());
        }
        var id = $(this).val();
        var options = $(this).data('options').filter('[value=' + id + ']');
        $('#select2').html(options);
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
      <select name="select1" id="select1">
        <option value="1">Fruit</option>
        <option value="2">Animal</option>
        <option value="3">Bird</option>
        <option value="4">Car</option>
      </select>
      
      
      <select name="select2" id="select2">
        <option value="1">Banana</option>
        <option value="1">Apple</option>
        <option value="1">Orange</option>
        <option value="2">Wolf</option>
        <option value="2">Fox</option>
        <option value="2">Bear</option>
        <option value="3">Eagle</option>
        <option value="3">Hawk</option>
        <option value="4">BWM<option>
      </select>

      使用jQuerydata()存储数据

      我猜隐藏元素不能跨浏览器工作(2012),我还没有测试过 我自己。

      【讨论】:

      • 很好的解决方案。我不知道.hide() 不工作 x-browser
      • @sabithpocker,我当然标记了它。一个小问题。我应该在这段代码中添加什么,当页面刚刚加载或刷新时,第二个选择已经只会显示水果选项 - 香蕉、苹果、橙子;不是所有选项。
      • @Randy $("#select1").trigger('change');这样您就可以显式调用更改事件。或者只是 $('#select1').change();也会这样做。
      • 上面的答案很好,我也没怎么改。我只注意到,如果我在表单中使用它,我无法区分“香蕉”、“苹果”、“橙色”,因为它们都具有相同的值 (1)。添加“数据值”解决了这个问题。
      • @Mauliardiwinoto 您还必须使用$(this).data('optionsForThird'... 存储第三个选择选项,然后对其进行过滤。请通过示例清楚地解释您的场景,例如 3 个选择如何相互关联。您可以发布问题,然后在此处添加链接作为评论。
      【解决方案4】:

      #select2的所有选项存储在一个变量中,根据#select1中所选选项的值过滤它们,并使用#select2中的.html()设置它们:

      var $select1 = $( '#select1' ),
          $select2 = $( '#select2' ),
          $options = $select2.find( 'option' );
      
      $select1.on('change', function() {
          $select2.html($options.filter('[value="' + this.value + '"]'));
      }).trigger('change'); 
      

      Here's a fiddle

      【讨论】:

      • @billyonecan。感谢您的代码,它看起来很容易理解,但如果我有更多两个选定的选项,如何根据前两个选定的选项显示,你能用小提琴解释一下吗?
      【解决方案5】:

      我找到了如下解决方案……完美地为我工作:)

      $(document).ready(function(){
      $("#selectbox1").change(function() {
          var id = $(this).val();
          $("#selectbox2").val(id);
       });   });
      

      【讨论】:

        【解决方案6】:

        所有这些方法都很棒。我发现了另一个简单的资源,它是使用 AJAX 的“onchange”创建动态表单的一个很好的例子。

        http://www.w3schools.com/php/php_ajax_database.asp

        我只是将文本表输出修改为基于第一个下拉列表的选择填充的另一个选择下拉列表。对于我的应用程序,用户将选择一个州,然后第二个下拉列表将填充所选州的城市。很像上面的 JSON 示例,但使用 php 和 mysql。

        【讨论】:

          【解决方案7】:

          我想制作一个使用来自单独 JSON 文件的 $.getJSON() 的版本。

          演示:here

          JavaScript:

          $(document).ready(function () {
              "use strict";
          
              var selectData, $states;
          
              function updateSelects() {
                  var cities = $.map(selectData[this.value], function (city) {
                      return $("<option />").text(city);
                  });
                  $("#city_names").empty().append(cities);
              }
          
              $.getJSON("updateSelect.json", function (data) {
                  var state;
                  selectData = data;
                  $states = $("#us_states").on("change", updateSelects);
                  for (state in selectData) {
                      $("<option />").text(state).appendTo($states);
                  }
                  $states.change();
              });
          });
          

          HTML:

          <!DOCTYPE html>
          <html>
          <head>
              <title></title>
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
          </head>
          <body>
              <select id="us_states"></select>
              <select id="city_names"></select>
              <script type="text/javascript" src="updateSelect.js"></script>
          </body>
          </html>
          

          JSON:

          {
              "NE": [
                  "Smallville",
                  "Bigville"
              ],
              "CA": [
                  "Sunnyvale",
                  "Druryburg",
                  "Vickslake"
              ],
              "MI": [
                  "Lakeside",
                  "Fireside",
                  "Chatsville"
              ]
          }
          

          【讨论】:

            【解决方案8】:

            我基于 sabithpocker 的想法制作了一个更通用的版本,让您可以从给定的触发器控制多个选择框。

            我为我想要控制的选择框分配了类名“switchable”,并像这样克隆它们:

            $j(this).data('options',$j('select.switchable option').clone());
            

            并为可切换选择使用特定的命名约定,这也可以转换为类。在我的例子中,“category”和“issuer”是选择名称,“category_2”和“issuer_1”是类名。

            然后我在 select.switchable 组上运行了一个 $.each,在复制 $(this) 以在函数内部使用之后:

            var that = this;
            $j("select.switchable").each(function() { 
                var thisname = $j(this).attr('name');
                var theseoptions = $j(that).data('options').filter( '.' + thisname + '_' + id );
                $j(this).html(theseoptions);
            });     
            

            通过在您想要控制的那些上使用类名,该函数将安全地忽略页面上其他地方的其他选择(例如 Fiddle 示例中的最后一个)。

            Here's a Fiddle 完整代码:

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2023-04-02
              • 2015-10-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-12-17
              相关资源
              最近更新 更多