Use jQuery to change a second select list based on the first select list option

后端 未结 8 2104
你的背包
你的背包 2020-11-22 14:34

I have two selects:


                        
    
提交评论

  • 2020-11-22 14:45

    I wanted to make a version of this that uses $.getJSON() from a separate JSON file.

    Demo: 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"
        ]
    }
    
    0 讨论(0)
  • 2020-11-22 14:47

    All of these methods are great. I have found another simple resource that is a great example of creating a dynamic form using "onchange" with AJAX.

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

    I simply modified the text table output to anther select dropdown populated based on the selection of the first drop down. For my application a user will select a state then the second dropdown will be populated with the cities for the selected state. Much like the JSON example above but with php and mysql.

    0 讨论(0)
  • 2020-11-22 14:47

    Try to use it:

    Drop-down box dependent on the option selected in another drop-down box. Use jQuery to change a second select list based on the first select list option.

    <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>
    

    Use jQuery library in your web page.

    <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>
    

    Use Backend code in your web page.

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 14:52

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

    Using jQuery data() to store data

    I guess hiding elements doesn't work cross-browser(2012), I have'nt tested it myself.

    0 讨论(0)
  • 2020-11-22 14:55

    I built on sabithpocker's idea and made a more generalized version that lets you control more than one selectbox from a given trigger.

    I assigned the selectboxes I wanted to be controlled the classname "switchable," and cloned them all like this:

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

    and used a specific naming convention for the switchable selects, which could also translate into classes. In my case, "category" and "issuer" were the select names, and "category_2" and "issuer_1" the class names.

    Then I ran an $.each on the select.switchable groups, after making a copy of $(this) for use inside the function:

    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);
    });     
    

    By using a classname on the ones you want to control, the function will safely ignore other selects elsewhere on the page (such as the last one in the example on Fiddle).

    Here's a Fiddle with the complete code:

    0 讨论(0)
  • 提交回复
    热议问题