Jacques Bronkhorst
Jacques Bronkhorst

Reputation: 1695

Change options value programmatically using Knockout

I have a options binding with knockout that looks like this:

<select id="ddlProducts" data-bind="options: ShowProducts, optionsText: 'pruductskuname', optionsCaption: 'Choose a product...', value: currentproduct"></select>

I have an ajax call that validates a serial number and return's a product name. I want to change the Selected Option to the return product. The return from my ajax call is the product name: pruductskuname

Is there a way to set the selected option based on my return?

For example if the return if my Return == ProductA I want to find in my Options ProductA and set the value to ProductA.

Here is my VM:

    /* Data View Model */
    var myDataViewModel = {
        products: ko.observableArray(),
        viewserialized: ko.observable(1),
        currentordernumer: ko.observable(),
        currentserialqty: ko.observable(),
        currentproduct: ko.observable(),
        dataitems: ko.observableArray()
    };

and here is my ajax call that gets the return message:

 $.ajax({
                url: "ServiceURL",
                data: { Serial: ko.toJS(myDataViewModel.currentserialqty) },
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "JSON",
                timeout: 10000,
                success: function (Result) {
                   /*SET OPTION BINDING HERE BASED ON Result.d */
                    alert(Result.d);
                },
                error: function (xhr, status) {
                    alert(status + " - " + xhr.responseText);
                }
            });

Upvotes: 3

Views: 2114

Answers (1)

Gabriel Sadaka
Gabriel Sadaka

Reputation: 1746

Well there are two ways of doing this, one would be to set the optionsValue to the pruductskuname like so:

 <select id="ddlProducts" data-bind="options: ShowProducts, optionsText: 'pruductskuname', optionsCaption: 'Choose a product...', value: currentproduct", optionsValue: 'pruductskuname'></select>

This will make currentproduct be equal to the name of the product, so all you would have to do in your success callback is myDataViewModel.currentproduct(Result.d);

If you don't do that you could

  myDataViewModel.currentproduct(ko.utils.arrayFirst(myDataViewModel.products(), function (item)
    {
        return item.pruductskuname() === Result.d;  //note the ()
    })

which will search for the item with that name and set it to the current product.

Upvotes: 2

Related Questions