Knockoutjs how to get selected arrayObject parameter

I want to get the selected option object

<select data-bind="options: availableCountries, value: selectedCountry, event: { select: onSelect}"></select> <script type="text/javascript"> // Constructor for an object with two properties 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 onSelect: function(){ console.log(viewModel.selectedCountry) // it is showing just an country name and what i what is whole object // eg { "UK", 65000000 } // that is selected option in selected box } }; </script> 
+6
source share
1 answer

You do not need to add a select event to the control. A more efficient way is to subscribe to selectedCountry changes:

 viewModel.selectedCountry.subscribe(function (data) { console.log(data) }); 

If you don’t want a country to be selected by default, you need to add the optionsCaption binding to data-bind :

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

The fiddle works here: http://jsfiddle.net/vyshniakov/tuMta/1/

+16
source

All Articles