Search code examples
knockout.jsknockout-3.0

Knockout select list - specify a default value


When binding data to a select list with objects, how do I go about specifying a default value?

I am trying in the following way:

var Country = function(name, population) {
  this.countryName = name;
  this.countryPopulation = population;
};

var viewModel = {
  availableCountries: ko.observableArray([
    new Country("UK", 65000000),
    new Country("USA", 320000000),
    new Country("Sweden", 29000000)
  ]),
  selectedCountry: ko.observable(new Country("USA", 320000000))
};

<select data-bind="options: availableCountries,
                   optionsText: 'countryName',
                   value: selectedCountry,
                   optionsCaption: 'Choose...'"></select>

The idea is that availableCountries will contain an array of Country objects, and the selected one gets held in the selectedCountry observable.

Everything works as expected, except when it comes to pre-selecting a value in the list.

I expect it's not working because they are actually different object references. What is the cleanest and simplest way of getting this to work? I want the USA country to be selected by default.

Here is a fiddle to illustrate the problem: https://jsfiddle.net/85crLcy2/


Solution

  • You can split out the array of choices and then set selectedCountry to the USA choice:

    var choices = [
        new Country("UK", 65000000),
        new Country("USA", 320000000),
        new Country("Sweden", 29000000)
      ];
    var viewModel = {
      availableCountries: ko.observableArray(choices),
      selectedCountry: ko.observable(choices[1])
    };