knockoutjs how to get the selected option arrayObject

穿精又带淫゛_ 提交于 2020-01-02 03:57:25

问题


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>

回答1:


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/



来源:https://stackoverflow.com/questions/14706784/knockoutjs-how-to-get-the-selected-option-arrayobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!