Search code examples
javascriptknockout.jsknockout-mapping-pluginknockout-2.0knockout-mvc

dropdown knockoutjs with value from server


I am working on a drop down menu within a TR .. I have true, false or none as the value that I receive from server and I want that to change the drop down option as in example below.

The first one is working but I want the second one to function as the first one

Example is here: http://jsfiddle.net/3xLgJ/

This is my HTML:

       <div data-bind='text: incomingValue'></div>

       <select data-bind="value: incomingValue">
             <option value="true">Yes</option>
             <option value="false">No</option>
             <option value="none">Don't Know</option>
      </select>

How can I implment this as above as this is within a tr and to function as above

      <select  data-bind='options: yesno, value: incomingValue'/>

Here is my knockout

    var myModelView = function () {
    self = this;
    self.yesno = ko.observableArray(['Yes', 'No', 'Don\'t know']);
    self.incomingValue = ko.observable('none');
    };

    var moView = new myModelView();

    ko.applyBindings(moView);  

Thanks

Thanks


Solution

  • The best solution is probably to slightly reconstruct the view model to use objects instead of simple strings:

    // Create a "class" that represents an option
    var Option = function(id, caption) {
        this.id = id;
        this.caption = caption;
    };
    

    Now you populate the observable array with objects constructed from this function:

    self.yesno = ko.observableArray([
        new Option('true', 'Yes'),
        new Option('false', 'No'),
        new Option('none', 'Don\'t know')
    ]);
    

    You can use the "optionsText" binding to correctly bind these objects to the markup:

    <select data-bind="options: yesno,
                       optionsText: 'caption',
                       value: selectedItem"></select>
    

    If you receive a string "none" from the server, you need to find the object representing this option:

    var incomingValue = 'none';
    
    // Find the first object that is a match in the observable array "yesno"
    var incomingItem = ko.utils.arrayFirst(self.yesno(), function(item) {
        return item.id == incomingValue;
    });
    
    self.selectedItem = ko.observable(incomingItem);
    

    When displaying the selection somewhere else you'll need to consider that the selection is represented by an object:

    <div data-bind='text: selectedItem().caption'></div>
    

    Demo: http://jsfiddle.net/3xLgJ/2/