Reputation: 519
i'm very new to knockout js and i'm trying my hands out on examples so i have this
<script>
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() // Nothing selected by default
};
$(function(){ko.applyBindings(viewModel)});
</script>
and in the view
<p>Your country:
<select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, 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>
my question is i want the drop down to have a pre-selected value at initialization so i tried this
selectedCountry : ko.observable(new Country("UK", 65000000))
but its not working "Choose..." still appears as the pre-selected optionsText instead of "Uk" then i tried
selectedCountry : ko.observable(availableCountries[0])
but i keep getting this error
"Uncaught TypeError: Cannot read property '0' of undefined "
what am i doing wrongly and how do i fix it?
Upvotes: 2
Views: 153
Reputation: 2853
after you define the viewModel object, add the following:
viewModel.selectedCountry(viewModel.availableCountries()[0]);
you cant reference a value on an object as its being declared (at least i dont think you can), so you would need to do the assignment after the fact.
another option is to define your viewModel as a function:
var viewModel = function (){
var self = this;
self.availableCountries = ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000)
]);
self.selectedCountry = ko.observable(self.availableCountries()[0])
};
Upvotes: 1
Reputation: 1891
I believe the solution to this is to set your selected value to "UK". As the value binding reads just the value not the entire object.
So when you set the object at index 0 that item isn't recognized as a value.
HTH
Upvotes: 0