简体   繁体   中英

Set selected value in knockout drop down list after populating it with AJAX

I have a drop down list on a page. I have knockout data binding on the drop down list.

By default the drop down list does not have any items in it. I have an AJAX call that works and retrieves the correct list of items for the drop down list.

After the list of items has been retrieved and loaded into the drop down list, how can I set the selected item of the drop down list?

<select class="form-control" data-bind="options: listOfPossibleValues, value: selectedValue, optionsCaption: 'Select a Value'"></select>

 $.ajax({
            type: 'GET',
            dataType: 'json',
            url: url,
            data: {
                someParameter: someParameterValue
            },
            success: function (response) {
                $.each(response, function (index, center) {
                    self.listOfPossibleValues.push(response[index]);
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log("There has been an error retrieving the values.");
            }
        });
<select class="form-control" data-bind="options: listOfPossibleValues, value: selectedValue, optionsCaption: 'Select a Value'"></select>

 $.ajax({
            type: 'GET',
            dataType: 'json',
            url: url,
            data: {
                someParameter: someParameterValue
            },
            success: function (response) {
                $.each(response, function (index, center) {
                    self.listOfPossibleValues.push(response[index]);
                });
                //set value here
                $(".form-control").val("xyz123");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log("There has been an error retrieving the values.");
            }
        });

You have to declare the selectedValue as observable and set the value like below:

self.selectedValue = ko.observable();
self.selectedValue("//what ever property value get from business model");

As you have selected value bound to knockout variable using data-bind=...value: selectedValue then you only need to assign it a new value (the selected one):

self.selectedValue('mySelectedValue');

Knockout will do the rest for you

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