KnockoutJS : how to set the initial value from a dropdown list when data is retrieved asynchronously using JSON?
http://stackoverflow.com/questions/8432278/knockoutjs-how-to-set-the-initial-value-from-a-dropdown-list-when-data-is-retr
by Himanshu Joshi
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedItem"></select>
<div data-bind="text: selectedItem"></div>
CSS
h2 { font-size: 1.1em; font-weight: bold; }
JavaScript
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
var viewModel = {
selectedItem: ko.observable(3),
items: ko.observableArray([new Item(3, "")])
};
ko.applyBindings(viewModel);
setTimeout(function() {
viewModel.items([
new Item(1, "pencil"),
new Item(2, "pen"),
new Item(3, "marker"),
new Item(4, "crayon")
]);
}, 500);