Rn.
Rn.

Reputation: 167

Not getting onchange event of dynamicly added dropdown in mvc3

I have three dropdownlists.

$(document).ready(function () {
        $("#DropDownList1").change(function () {
            $("#Id1").val($(this).val());
            $("#Name1").val($("#DropDownList1 option:selected").text());
            $('#Div1').load('/Account/Dropdown2/?Id1=' + $("#Id1").val());

        });
        $("#DropDownList2").change(function () {
            $("#routeId").val($(this).val());
            $("#routeName").val($("#RouteDropDownList option:selected").text());
            $('#Div2').load('/Account/Dropdown3/?Id2=' + $("#routeId").val());


        });
        $("#DropDownList3").change(function () {
            $("#Id3").val($(this).val());
            $("#Name3").val($("#DropDownList3 option:selected").text());


        });
    });

In this DropDownList2 and DropDownList3 are added dynamicly.The problem is the dynamicly added dropdowns are not got registered in the page .So I am not getting its selected value from the onchange event.I added these controls as partial view. Controller.

public ActionResult DropDownList2 (string Id1)
        {
            List<Emp> empList = new List<Emp>();
            Emp em= new Emp ()
            {
                Id = "1",
                Name = "Doac"
            };            
            empList .Add(em);            
            ViewBag.DropDownList2= new SelectList(empList , "Id", "Name");
            return PartialView();
        }

Generated Html

<script type="text/javascript">
    $('#CreateSubscriber').removeClass('menuHolderli').addClass('selectedMenu');
    $(document).ready(function () {
        $("#DropDownList").change(function () {
            $("#Organization_Id").val($(this).val());
            $("#Organization_Name").val($("#DropDownList option:selected").text());
            $('#routeDiv').load('/Account/RouteDropdown/?organizationId=' + $("#Organization_Id").val());

        });
        $(document).on('change', "#RouteDropDownList", function () {
            alert("hi");
            $("#routeId").val($(this).val());
            $("#routeName").val($("#RouteDropDownList option:selected").text());
            $('#locationDiv').load('/Account/LocationDropdown/?routeId=' + $("#routeId").val());

        });
        $("#LocationDropDownList").change(function () {
            $("#locationId").val($(this).val());
            $("#locationName").val($("#LocationDropDownList option:selected").text());


        });
    });
</script>
<p class="message-info">
    Passwords are required to be a minimum of 6 characters in length.
</p>

<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

<form action="/Account/Register" method="post">    <fieldset>
        <legend>Registration Form</legend>
        <ol>
            <li>

                <label for="Organization_Name">Name</label>
                <input id="Organization_Id" name="Organization.Id" type="hidden" value="" />
                <input id="Organization_Name" name="Organization.Name" type="hidden" value="" />

                <select id="DropDownList" name="DropDownList"><option value="">---Select---</option>
<option value="516c0a18c891870f107aa74a">Choice School</option>
<option value="516d277bc8918701a44c131e">New Org</option>
<option value="516d1f492e6bba07dc245cc7">Olive</option>
</select>
                <span class="field-validation-valid" data-valmsg-for="Organization.Name" data-valmsg-replace="true"></span>
            </li>
        </ol>

        <div id="routeDiv"></div>
        <div id="locationDiv"></div>

Upvotes: 0

Views: 1494

Answers (3)

Aaron Vanderwielen
Aaron Vanderwielen

Reputation: 237

If you are adding the select options dynamically, why not use AJAX within AJAX?

$(function() {
    $('#DropDownList').each(function () {
        var dropdown = $(this);

        dropdown.change(function() {
            $.ajax({
                url: 'Account/GetDropDownOptions',
                type: 'GET',
                data: {dropdownID: dropdown.attr('id'), value: dropdown.val()},
                dataType: 'html',
                cache: false,
                success: function (data) {
                    var dropdown2 = $('#DropDownList2');
                    dropdown2.html(data);

                    dropdown2.change(function() {
                        $.ajax({
                            url: 'Account/GetDropDownOptions',
                            type: 'GET',
                            data: {dropdownID: dropdown2.attr('id'), value: dropdown2.val()},
                            dataType: 'html',
                            cache: false,
                            success: function (data) {
                                var dropdown3 = $('#DropDownList3');
                                dropdown3.html(data);

                                dropdown3.change(function() {
                                    //....same thing as above pretty much
                                });
                            }
                        });
                    });
                }
            });
        });
    });
});

Then your controller action, GetDropDownOptions, would examine the DDL ID and selected value, understand what options it needed, then return the options as HTML. Or as a more elegant solution, you could have it return an object as json ( return Json(object) ) and then programatically create the elements in your javascript. You'd have to switch the dataType in the $.ajax to 'json'.

This way you have the dropdown change event after it has loaded the options. This change event loads DropDownList2's options and change event, which will load DDL3's options.

Haven't tested the code, but this idea will work. This sample assumes you already have the first DDL options loaded, but it seems you'll have to have add another layer of ajax to load those in as well. It also assumes the and DDL3 are already on the DOM at page load. You could add them to the DOM in your html to get this example to work, or change the IDs in the javascript to some container.

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Use jQuery .on()

$(document).on('change', "#DropDownList2", function(){your code})

Repeat for your dropdown 3

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

Since, DropDownList2 and DropDownList3 are added dynamicly, you need to do this:

$(document).on('change', '#DropDownList1', (function () {
    $("#Id1").val($(this).val());
    $("#Name1").val($("#DropDownList1 option:selected").text());
    $('#Div1').load('/Account/Dropdown2/?Id1=' + $("#Id1").val());
});

Similarly call other dyanmically added dropdowns also.

Upvotes: 0

Related Questions