0

I have two DropDownList in cascade

DD2 dependent on DD1.

how do I disable the DD2 if the D1 does not contain data for the selected item?

 $(function () {
         $('#DD1').change(function () {
             var selected1 = $(this).val();
             $.getJSON('@Url.Action("GetCiudadList", "ConsultorioSuper", new { Area = "Superusuario", controller = "Consultorio" })', { IdDD: selected }, function (myData) {
                 var Select2 = $('#DD2');
                 Select2.empty();
                 $.each(myData, function (index, itemData) {
                     citiesSelect.append($('<option/>', {
                         value: itemData.Value,
                         text: itemData.Text
                     }));
                 });
             });
         });

     })

 @Html.DropDownListFor(x => x.SelectedId1, new SelectList(ViewBag.IdUniversidad, "Id1", "Name"), "-- Select --", new { id = "DD1" })
 @Html.DropDownListFor(x => x.SelectedId2, new SelectList(Enumerable.Empty<SelectListItem>(), "Id2", "Name"), "-- Select --", new { id = "DD2" })

Blessings

1 Answer 1

1

how do I disable the DD2 if the D1 does not contain data for the selected item?

How do you know that D1 doesn't contain data for the selected item? What does your controller action return in this case? An empty array I guess. If that's the case a simple if condition would do the job:

$.getJSON('@Url.Action("GetCiudadList", "ConsultorioSuper", new { Area = "Superusuario", controller = "Consultorio" })', { IdDD: selected }, function (myData) {
    var Select2 = $('#DD2');
    if (myData.length == null || myData.length == 0) {
        // null or empty data => disable the second ddl and stop executing
        // this function
        Select2.attr('disabled', 'disabled');
        return;
    }

    // at this stage we know that the myData array contains element =>
    // rebind the second dropdown list with those elements
    Select2.empty();
    $.each(myData, function (index, itemData) {
        citiesSelect.append($('<option/>', {
            value: itemData.Value,
            text: itemData.Text
        }));
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hello @Darin Dimitrov Thanks but now, how do I enable the DD2 if the D1 contain data for the selected item?
Select2.removeAttr('disabled');. I would recommend you heading towards the jQuery documentation and read some getting started tutorials: docs.jquery.com/Main_Page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.