knockout.js Options


Example

Use this binding to build options for a select item

<select data-bind="options: gasGiants"></select>
 
<script type="text/javascript">
    var viewModel = {
        gasGiants: ko.observableArray(['Jupiter', 'Saturn', 'Neptune', 'Uranus'])
    };
</script>

You can also use properties inside the array for displaying in the list and for saving in the viewModel: optionsText enables a custom display text

optionsValue sets the value property of the corresponding <option>

value stores the value of the selected option into an observable of the viewModel

<select data-bind="options: gasGiants, optionsText:'name', optionsValue:'id', value:selectedPlanetId"></select>
 
<script type="text/javascript">
    var viewModel = {
        selectedPlanetId: ko.observable(),
        gasGiants: ko.observableArray([{name:'Jupiter', id:'0'},
                                       {name:'Saturn', id:'1'},
                                       {name:'Neptune', id:'2'},
                                       {name:'Uranus', id:'3'}])
    };
</script>

To store the results of a multi-select list, the options binding can be combined with the selectedOptions binding.

<select data-bind="options: gasGiants, selectedOptions: chosenGasGiants" multiple="true"></select>

<script type="text/javascript">
    var viewModel = {
        gasGiants: ko.observableArray(['Jupiter', 'Saturn', 'Neptune', 'Uranus'])
        chosenGasGiants: ko.observableArray(['Jupiter','Saturn']) // Initial selection
    }; </script>