Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating One Select Box Based on the Selection in Another Select Box - JQuery?

Tags:

jquery

I am trying to populate one select box based on the selection made in the first select box. I've looked online, and found a lot of helpful information on hard-coded options, but I need my options to come from a query (like cfquery in coldfusion). I know that a cfquery is server-side, so I cannot include it in my jquery, but is there another option?

I was using the following example:

HTML:

<select id="counties">
    <option> </option>
    <option> somerset </option>
    <option> hertfordshire </option>
</select>

<select id="towns" disabled="true">
</select>

JS:

var countyTowns = [
    ["Bath", "Bristol"],
    ["Letchworth", "Hitchin"]
];

$("#counties").change(function() {
    var county = this.selectedIndex - 1;
    $("#towns").empty();
    if (county === -1) {
        $("#towns").attr("disabled", true);
    } else {
        var towns = countyTowns[county];
        for (var i = 0; i < towns.length; i++) {
            $("#towns").append($("<option></option>").text(towns[i]));
        }
        $("#towns").attr("disabled", false);
    }
});

What I would need is for towns to be dynamic, and able to be read from a database.

Any help is greatly appreciated!

Thanks

like image 536
shawleigh17 Avatar asked May 02 '11 18:05

shawleigh17


1 Answers

as you mentioned that : towns to be dynamic, and able to be read from a database you can get dynamic data by passing it with ajax.

Ajax Get from controller to read from database based Country which user has selected:

 <script>
        $(document).ready(function () {
           $("#counties").on('change', function () {
                var selectedItem = $(this).val();
                var ddlStates = $("#towns"); // will be update after success ajax call
                var statesProgress = $("#states-loading-progress");
                statesProgress.show();
                $.ajax({     // get states/towns from db from controller
                    cache: false,
                    type: "GET",
                    url: "@(Url.RouteUrl("GetStatesByCountryId"))", 

                    data: { "countryId": selectedItem, "addSelectStateItem": "true" },
                    success: function (data) { 
                        ddlStates.html('');
                        $.each(data, function (id, option) {
                            ddlStates.append($('<option></option>').val(option.id).html(option.name)); 
                        });  // populating result 
                        statesProgress.hide(); // hide loader
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve states.');
                        statesProgress.hide();
                    }
                });
            });
        });
    </script>

And on controller :

  public virtual IActionResult GetStatesByCountryId(string countryId, bool addSelectStateItem)
    {
        var model = _countryModelFactory.GetStatesByCountryId(countryId, addSelectStateItem);
        return Json(model);
    }

Then on Data access layer _countryModelFactory.GetStatesByCountryId()i get towns/states from db based the country/town user has selected.

Update : It's the way i retrieving states/towns from db (dynamic country/towns) and populating them to selectboxin my code.

like image 54
Mohammad Avatar answered Oct 26 '22 10:10

Mohammad