Populate item to dropdown by using ajax call and a

2019-09-01 10:49发布

问题:

Please see my code below

$(document).ready(function () {
    readddl().done(function () {
        $('#ddlAreas').val("51");
    });

    $("#plusBtn").bind("vclick", function () {
        $('#ddlAreas').val("51");
    });
});

function readddl() {
    var df = $.Deferred();
    var stateID = 18;
    var dropdwonlist = $('#ddlAreas');
    dropdwonlist.empty();
    dropdwonlist.append($('<option></option>').val("--").html("Select Area"));

    if (stateID != undefined && stateID != "--") {
        // Send an AJAX request
        $.getJSON(Config.Url + "Area?status=A&&stateID=" + stateID)
            .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (index, item) {
                // Add a list item for the product.
                dropdwonlist.append($('<option></option>').val(item.AREA_ID).html(item.AREA_NAME));

            });
        }).fail(function (d) {
            alert(d);
        })

    }
    return df.promise();
}

I am able to populate item to the dropdown. But i cant set selected value to dropdown. I also try set the selected value by clicking the plus button and it work

Please guide me solution. Thanks

回答1:

jQuery does not fire the change event when you use val(), so you have to do it yourself for the changes to take effect:

dropdwonlist.val(item.AREA_ID).change();

or

dropdwonlist.val(item.AREA_ID).trigger('change');