Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs how to get the selected option arrayObject

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>
like image 755
Anil Gupta Avatar asked Feb 05 '13 11:02

Anil Gupta


People also ask

How do you activate a Knockoutjs model?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

How do you update items in Observablearray knockout?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is Knockoutjs used for?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.


1 Answers

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/

like image 185
Artem Vyshniakov Avatar answered Oct 29 '22 00:10

Artem Vyshniakov