KnockoutJS selectedOptions Binding

In the last article we studied options binding which binds an array in view model with the select element of the form in html view. We saw how multiple and size tags were used to add multiple selected items to the list. In this article we shall study knockoutJS selectedOptions Binding. This type of binding is used to set the elements in the list that are currently selected. The knockoutJS selectedOptions binding is used in conjunction with option binding.

It is important to note here that, whenever user selects one or more than one items from the list, these items are added to the selected objects array in the view model. Similarly, if items are added to the view model array via push or splice method, the selection reflects in the HTML list in the view. Take a look at the following example to understand this concept.

KnockoutJS selectedOptions Binding Example

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    

 <p>
    Select Fruits:
    <select data-bind="options: fruits" size="7" multiple="true"> </select>
</p>
 
 <script type="text/javascript">
     function FruitModel() {
         var self = this;
         self.fruits = ko.observableArray(['Apple', 'Orange', 'Banana','Guava', 'Peach']);
 
     }

</script>
    
</body>
</html>

Download the code Try the code

The above code is quite similar to one we had in the last tutorial. However, in this case in the binding section we have an initial binding i.e. selectedOptions whose value is set to chosenfruits. Now if you come down to the view model in the script section you have two arrays. The first array fruits binds all the fruits with the select element in the html view. While the items in the chosenfruits array are the items that are actually selected by the user.

If you open the above page in browser, you should see a list of fruits where only “Orange” shall be selected. If you deselect it, the it will be removed from chosenfruits array. Similarly, if you add any fruit into array via push method, you should see the elements appear selected in the list. This shows that selectedOptions binding is also two-way binding.

<<< KnockoutJS Options Binding
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .