<script src="http://knockoutjs.com/downloads/knockout-2.1.0.js"></script>
<p>How can I make the the below select the correct option when the options arrive? Expected 'option2' to be selected.</p>
<select data-bind="options: $data.choice.options, optionsText: 'text', optionsValue: 'value', value: $data.choice"></select>
JavaScript
var optionsProvider = (function () {
"use strict";
var self = {};
//container for options data, a sort of dictionary of option arrays.
self.options = {};
self.init = function (optionData) {
//pre-populate any provided options data here...
};
self.get = function(name, initialValue) {
if (!self.options[name]) {
self.options[name] = ko.observableArray([{ value: initialValue }]);
//ajax request for options
//populate self.options[name] with options upon return
//dummy this with below for example.
setTimeout(function() {
self.options[name]([
{ text : "option1", value : 1 },
{ text : "option2", value : 2 },
{ text : "option3", value : 3 },
]);
}, 1000); //simulate some delay
}
//return reference to observable immediately.
return self.options[name];
};
return self;
})();
var simpleModel = function() {
var initialValue = 2;
this.choice = ko.observable(initialValue); //hard code selected option to simulated pre-saved selection.
this.choice.options = optionsProvider.get("SomeOptionType", initialValue);
};
ko.applyBindings(new simpleModel());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.