Search code examples
knockout.jsko.observablearray

Populating a dropdown with an observable array in knockout.js


I have X number of dropdowns that I dynamically created using Knockout, and now I want to preselect one option per dropdown. Coincidentally, I have an observable array with X entries that correspond to the options I want selected. How can I use this array to select my options?

Example viewmodel:

function AppViewModel() {
    var self = this;
    self.array = ko.observable(["Dog","Cat"]);
}

In this example, I have two dropdowns, both of which have a "Dog" and "Cat" option. I want to select "Dog" for the first dropdown and "Cat" for the second.

Here's my HTML:

<div data-bind="foreach: array">
      <label>
        <select data-bind="options: array"></select>
      </label>
</div>

Solution

  • As per the docs you need a value binding for your selected binding.

    function AppViewModel() {
        var self = this;
        self.array = ko.observable(["Dog","Cat"]);
        self.selected = ko.observable(self.array()[0]);
    }
    

    And then:

    <select data-bind="options: array, value: selected "></select>
    

    Example: http://jsfiddle.net/H6DL5/

    If you've got many of these dropdowns, then you can use an array of subVMs for your result. Something like this:

    function AppViewModel() {
        var self = this;
        self.array = ko.observable(["Dog", "Cat", "Weasel"]);
        self.dropDowns = ko.observableArray([
        new SubVM("Dog"),
        new SubVM("Cat")]);
    }
    
    function SubVM(selected) {
        var self = this;
        self.selected = ko.observable(selected);
    }
    

    Which you can bind like this:

    <div data-bind="foreach:dropDowns">
        <select data-bind="options: $parent.array, value: selected "></select>
    </div>
    

    Now you can add as many drop-downs as you need by adding them to the dropDowns array in your parent VM.

    Example: http://jsfiddle.net/H6DL5/1/

    If you need different options in each drop-down, just add an array for the available options to your SubVM and bind for options that instead of the parent list.