Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the selected option in a dropdown after receiving a result from ajax call

Tags:

knockout.js

I use the the following ViewModel

<script type='text/javascript'>
$(function () {

    var dropdownCtor = function (text, value, defaultValue) {
        this.text = text;
        this.value = value;
        this.defaultValue = defaultValue;
    };

    var productsViewCtor = function () {

        var self = this;

        this.productType = ko.observable();
        this.productTypes = ko.observableArray(['Summer', 'Winter']);
        this.products = ko.observableArray();
        this.product = ko.observable();

        this.productType.subscribe(function (newProductType) {


            $.post(
        '/Home/GetProducts',
        { productType: newProductType },
        function (resultProducts) {
            self.products(resultProducts);
            self.product(resultProducts[2]);
        });

        } .bind(this));

    }
    var productViewModel = new productsViewCtor();

    ko.applyBindings(productViewModel);

});

An the following Html

<h3> Your Products:</h3>
<p>
     <span><select data-bind="options: productTypes, value: productType"></select></span>
   <span>
   <select data-bind="options: products , optionsText: 'text' ,  optionsValue: 'value' , value: product"></select></span>
</p>
<ol class="round">
 <li >
        <h5   >productType</h5>
       <span data-bind="text: productType"></span>
    </li>
     <li >
        <h5   >product</h5>
       <span data-bind="text: product"></span>
    </li>
</ol>

When the page loads the ajax call is sent and I receive all the products for winter. They are displayed inthe dropdown and the selected value is 101.

By selecting "summer" in the productType dropdown I try to load the producst again. This is also successfull. But then I want to preselect an option (here the 3rd one) by setting a specific product in the VoewModel. This product is not selected in the dropdown and also not displayed inside the span tag.

How can I select an item in the dropdown?

like image 912
Mathias F Avatar asked Mar 03 '12 22:03

Mathias F


1 Answers

You specified the optionsValue binding on your product select to be 'value'. This is the property that will be bound by the value binding to product.

So you need to do:

self.product(resultProducts[2].value);

Here is a fiddle where I demonstrate this. The sub options I load are an object, and I have to set my selectedSubOption to the id I want.

http://jsfiddle.net/jearles/Z7jzr/

like image 97
John Earles Avatar answered Oct 15 '22 15:10

John Earles