<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>
Your country:
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountryCode,
optionsValue: 'countryCode',
optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
JavaScript
// Constructor for an object with two properties
var Country = function(name, population, code) {
this.countryName = name;
this.countryPopulation = population;
this.coutryCode = code;
};
var viewModel = {
var self = this;
availableCountries = ko.observableArray([
new Country("United Kingdom", 65000000, "UK"),
new Country("United States", 320000000, "USA"),
new Country("Sweden", 29000000, "SWE")
]);
selectedCountryCode = ko.observable(self.availableCountries[0].countryName); // Nothing selected by default
selectedCountry = ko.computed(function () {
return ko.utils.arrayFirst(availableCountries, function(item){
return item.coutryCode === selectedCountryCode();
})
});
};
ko.applyBindings(viewModel);
console.log(viewModel.availableCountries());
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.