Search code examples
knockout.jsknockout-mapping-plugin

Binding a select-list's value


I have a setup very similar to the following jsfiddle: http://jsfiddle.net/EM9Rh/72/ In my implementation I am using the mapping plugin to map my MVC Model to a JS Model for binding.

Implementation: Select-Binding

<span data-bind="with: Value">
     <select data-bind="options: DropDown.Options, optionsValue: $data, optionsText: 'Name', value: Selected"></select>
</span>

Question(s):

How do I map the value of a select-list (like the one above) to one of the options? Notice my JSON object in the JSFiddle, How do I map it so that the select starts with option '3' selected?

How do I map the value of a select-list in the JSFiddle? (Asking both encase it differs due to use of the mapping-plugin).

I've read both the documentation for option/select-binding and the mapping plugin but I just can't seem to get it to work. I've tried data-bind=".....value: Selected" but it never sets and actually messes what does work up.


Solution

  • You just have to set the value of selected to the object that you want selected:

    SetSelectToItem: function(item) {
       this.Value.Selected(this.Value.DropDown.Options[item-1]);   
    }
    

    JSFiddle

    Note that object equality requires you set it to the object itself, not an identical object. See this question for details on that.