Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a dropdown for Country, State, and City. Country to State Javascript onchange works fine. Now I want to populate the cities dropdown. I created another onchange event but it is not working and I am thinking it is not working because the dropdown is repopulated by the JavaScript. The original dropdown before populated is a @Html.DropdownListFor this is replaced by an Html options select by JavaScript. My question is how do I rearrange the JavaScript code so that I can add the cities dropdown. Below is the JavaScript code and View of the 3 items in the View.


Thanks for your help!

What I have tried:

View:
C#
<div class="form-group">
    @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => Model.Country, Model.Countries, "---Select Country---", new { @class = "form-control", @id = "ddlCountry" })
        @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
    <div id="State" class="col-md-10">
        @Html.DropDownListFor(model => model.State, new List<SelectListItem>(),"---Select State---", new { @class = "form-control", @id = "ddlState" })
        @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
    <div id="City" class="col-md-10">
        @Html.DropDownListFor(model => model.City, new List<SelectListItem>(), "---Select City---", new { @class = "form-control"})
        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
    </div>
</div>



JavaScript:

JavaScript
<script type="text/javascript">
    $(function () {
        $('#ddlCountry').change(function () {
            $.ajax({
                type: "post",
                url: "/Addresses/GetStates",
                data: { countryId: $('#ddlCountry').val() },
                datatype: "json",
                traditional: true,
                success: function (data) {
                    var st = "<select class='form-control' id='ddlState'>";
                    st = st + '<option value="">--Select State--</option>';
                    for (var i = 0; i < data.length; i++) {
                        st = st + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
                    }
                    st = st + '</select>';
                    $('#State').html(st);
                }
            });
        });
    });

    $(function () {
        $('#ddlState').change(function () {
            $.ajax({
                type: "post",
                url: "/Addresses/GetCities",
                data: { stateId: $('#ddlState').val() },
                datatype: "json",
                traditional: true,
                success: function (data) {
                    var ct = "<select  class='form-control' id='ddlCity'>";
                    ct = ct + '<option value="">--Select City--</option>';
                    for (var i = 0; i < data.length; i++) {
                        ct = ct + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
                    }
                    ct = ct + '</select>';
                    $('#City').html(ct);
                }
            });
        });
    });
</script>
Posted
Updated 6-Nov-18 4:17am

1 solution

You wire up an event handler for a specific element. You then completely replace that element, which means the new element doesn't have any event handlers.

You could solve the problem by using delegated events[^]. But there's a simpler solution.

Rather than replacing the entire <select> element, just replace the options within it:
JavaScript
$(function(){
    $('#ddlCountry').change(function(){
        $.ajax({
            type: "post",
            url: "/Addresses/GetStates",
            data: { countryId: $(this).val() },
            datatype: "json",
            traditional: true
        }).then(function(data){
            var list = $("#ddlState");
            var stateId = list.val();
            
            list.empty();
            
            $.each(data, function(index, item){
                var opt = $("<option/>").attr("value", item.Value).text(item.Text);
                list.append(opt);
            });
            
            list.val(stateId);
        });
    });
    
    $('#ddlState').change(function(){
        $.ajax({
            type: "post",
            url: "/Addresses/GetCities",
            data: { stateId: $(this).val() },
            datatype: "json",
            traditional: true
        }).then(function(data){
            var list = $("#ddlCity");
            var cityId = list.val();
            
            list.empty();
            
            $.each(data, function(index, item){
                var opt = $("<option/>").attr("value", item.Value).text(item.Text);
                list.append(opt);
            });
            
            list.val(cityId);
        });
    });
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900