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

I have two selects:

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

How do I do that with jQuery if I choose Fruit in the first select? The second select would show me only Fruits - Banana, Apple, Orange. If I choose Bird in the first select, the second select would show me only Birds - Eagle, Hawk. And so on...

I tried to do it with this piece of jQuery code:

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

Unfortunately, it removes almost everything, and I have no idea how to bring back some options. I also read something about clone, but I don't know how to use it in this case.

This question is related to jquery html select

The answer is


On the selected answer I see that when initially the page is loaded the selection of first option is prior fixed and therefore gives the option of all the categories in selection 2. You can avoid that by adding the first option as the following in both the select tag:- <option value="none" selected disabled hidden>Select an Option</option>

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

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.


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"
    ]
}

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:


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

I have found the solution as followiing... working for me perfectly :)

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

Store all #select2's options in a variable, filter them according to the value of the chosen option in #select1, and set them using .html() in #select2:

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


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working