Knockout - dropdown

by Jakub Jedryszek

HTML

<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());