How to pre-select an option in a dropdown knockout js

http://stackoverflow.com/questions/8449824/how-to-pre-select-an-option-in-a-dropdown-knockout-js

by Keyur Patel

HTML

<select data-bind="options: choices, optionsText: 'name', value: choice"></select>

JavaScript

ko.observableArray.fn.find = function(prop, data) {
    var valueToMatch = data[prop]; 
    return ko.utils.arrayFirst(this(), function(item) {
        return item[prop] === valueToMatch; 
    });
};

function ViewModel(choices, choice) {
   this.choices = ko.observableArray(choices);
   this.choice = ko.observable(this.choices.find("id", choice)); 
};


var choices = [
        { id: 1, name: "one" },
        { id: 2, name: "two" },
        { id: 3, name: "three" }
    ];

var choice = { id: 2, name: "two" };



ko.applyBindings(new ViewModel(choices, choice));