Search code examples
jqueryasp.net-mvcvb.netdropdown

Dropdown list not updating after appending from ajax


When loading selectlistitem to dropdown from AJAX, it initially displays blank instead of the options. I'm not sure if this is an IE limitation but it works fine on Firefox.

I tried triggering change after append like this

$(ddlUpdate).trigger('change', true);

and

adding the following after append with no luck

$(ddlUpdate).trigger("chosen:updated");
$(ddlUpdate).trigger("liszt:updated");

Here is how the on change is being triggered

$('#ddlDistrictName').change(function () {
        getTerritory($('#ddlSalesOffice').val(), $(this).val(), $('#ddlTerritoryName'));});

function getTerritory(branch,area , ddlUpdate) {
    $.ajax({
        url: "/instSearch/GetTerritory",
        data: { branch: branch, area: area },
        dataType: "json",
        type: "GET",
        error: function () {
            alert(" An error occurred.");
        },
        success: function (data) {
            $(ddlUpdate).empty();
            $.each(data, function (i) {
                var optionhtml = '<option value="' +
                    data[i].Value + '">' + data[i].Text + '</option>';
                $(ddlUpdate).append(optionhtml);
                $(ddlUpdate).trigger("liszt:updated");
            });
        }
    });

}

The data is a JSON returned by a JsonResult

<HttpGet()>
     Public Function GetTerritory(ByVal branch As String, ByVal area As String) As JsonResult

    'サービスインスタンス
    Dim service As New InstSearchService(Me.ATOOLS)
    Dim ddl As IEnumerable(Of SelectListItem) = New List(Of SelectListItem)

    ddl = service.GetTerritory(branch, area)

    Return Json(ddl, JsonRequestBehavior.AllowGet)

End Function

When viewing the DOM, the updated list is being displayed. But when clicking the dropdown, it shows blank on the first click, and shows the entire list on the 2nd click.

enter image description here

What am I missing?


Solution

  • Seems like this is only happening in IE. So what i did was to surround the dropdown with a div, empty the div. and re append the dropdown. This way, it works normally on IE.

     $('.ddlTerritoryHolder').empty();
     $(territoryDdl).append(blankOption).appendTo('.ddlTerritoryHolder');