KnockoutJS Options Binding

Till now we have been studying binding that bind input fields with singular data like a text box or a paragraph etc. What if we want to bind control that contains multiple options with properties in view model. For instance, what if we have a drop down list and we want it to contain elements that exist in an array type property in object model. In such scenarios, we use KnocoutJS options binding. The options binding are used to bind an array in JavaScript view model with a HTML DOM select element. The select element will display each item from the view model array as one option in the select element. You can also use multiple select element using “select size=5” (for example to select 5 elements.) Take a look at the following example to see KnockoutJS options binding in action.

KnockoutJS Options 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"></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

Take a careful look at the above code. It contains a model in the view model named “FruitModel”. The model further contains an array “fruits” which contains name of some fruits. Now come above in the html view. Here we have a select element. Using the options binding, the items of the select elements are bound to the elements in the fruit array. Now if you open the above page in the browser, you should see dropdown list with all the elements in the fruits array.

KnocoutJS Multi-Select List

Using options binding, you can also create lists where you can select multiple items from the list. The following example demonstrates that.

<!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

Now if you look at the code, what we have done here is that we have added size attribute to the binding and set it to 7. This means that 7 items can simultaneously be selected from this list. The second attribute added to the options binding is multiple which is set to true. This specifies that multiple items can be selected from this list.

<<< KnockoutJS TextInput BindingKnockoutJS selectedOptions Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .