knockoutjs how to get the selected option arrayObject
11,252
You don't have to add select event to the control. More efficient way is to subscribe on selectedCountry
changes:
viewModel.selectedCountry.subscribe(function (data) {
console.log(data)
});
If you don't want any country is selected by default you have to add optionsCaption
binding to the data-bind
:
<select data-bind="options: availableCountries,
optionsText: 'countryName',
value: selectedCountry,
optionsCaption: 'Select...'"></select>
Here is working fiddle: http://jsfiddle.net/vyshniakov/tuMta/1/
![Anil Gupta](https://i.stack.imgur.com/Vw6Hl.jpg?s=256&g=1)
Author by
Anil Gupta
Updated on June 07, 2022Comments
-
Anil Gupta about 2 years
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 // e.g. { "UK", 65000000 } // that is selected option in selected box } }; </script>
-
Anil Gupta over 11 yearsconsole.log(data) // dump only string of selected value and i want associate data array
-
Artem Vyshniakov over 11 yearsIt doesn't return just a string, it returns selected element of array(i.e. Object { countryName= "UK", countryPopulation=65000000}).
-
Artem Vyshniakov over 11 yearsYou get just a string in selecetedCountery because of optionsValue:'name'. Remove it from the binding.