简体   繁体   中英

Setting the selected option using jQuery

I am loading an Option element using jQuery and when I try to set the selected option, it does not work. Can someone show me what I need to change to fix it.

HTML

<select data-placeholder="Program View" class="chosen-select"></select>

jQuery

$.getJSON(path)
.done(function (data) {
    if (!data) {
        return
    }

    setTimeout(
        function () {
            var loadedAtLeastOneProgram = false;

            $.each(data, function (i, val) {
                if (val.Value.toLowerCase() != "rt") {
                    loadedAtLeastOneProgram = true;
                    $('.chosen-select').append('<option value="' + val.Value + '">' + val.Value + '</option>')
                }
            })

            $('.chosen-select').trigger('chosen:updated');

            if (!loadedAtLeastOneProgram) {
                $("#programsDataItems").append("<li><a href='#'>No Tailored Programs Available</a></li>");
            }

            // After loading (or reloading) the programs, see if one was previously selected. The user may have refreshed their browser.
            // In another part of my application, I set the "CurrentProgram"
            var program = retrieveStorageItem("CurrentProgram");

            if (program == null || program == undefined) {
                program = "rt";
            } else {
                // ***** This is the part that does not work. Nothing shows as selected. ******
                $(".chosen-select").val(program).prop('selected', true);
            }

        }, 50);

})
.fail(function (e) {
    // Adding logging for errors.
});
$('.chosen-select').trigger('chosen:updated');

this is what you need to fire to apply the selection.

else {
            // ***** This is the part that does not work. Nothing shows as selected. ******
            $(".chosen-select").val(program).prop('selected', true);
            $('.chosen-select').trigger('chosen:updated'); //added
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM