KnockoutJS - selectedOptions Binding



This binding is used to work with elements which are selected currently in the multi list select form control. This binding can be used with option binding and <select> form control only.

When the user selects or de-selects an item in the multi-select list, this adds or removes the corresponding value to an array on the view model. If it is an Observable array then then the items selected or de-selected from the UI are also updated in the array in ViewModel, making it a two-way binding method.

Syntax

selectedOptions: <binding-array>

Parameters

  • Parameter here will be an array (can also be an Observable). The active items from select element are stored into this array. Earlier items will be overwritten.

  • If the parameter is Observable array, then the items selected are updated as and when the underlying observable is changed. Element is processed only once, if no Observable array is used.

Example

Let us take a look at the following example which demonstrates the use of selectedOptions Binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS selectedOptions Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Tutorials Library:<br><br>
      <select size = 10 multiple = 'true' data-bind = "
         options: availableTutorials,
         selectedOptions: selectedTutorials
      "></select></p>
         
      <p>(Press control and select for multiple options.)</p>
      <p>You have chosen below Tutorials:</p>
      <ul data-bind = "foreach: selectedTutorials">
         <li>
            <span data-bind = "text: $data"> </span>
         </li>
      </ul>

      <script type = "text/javascript">
         function ViewModel() {
            self = this;
            self.availableTutorials = ko.observableArray ([
               'Academic','Big Data','Databases',
               'Java Technologies','Mainframe',
               'Management','Microsoft Technologies',
               'Mobile Development','Programming','Software Quality'
            ]);

            self.selectedTutorials = ko.observableArray();
         };
         
         var vm = new ViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in selectedoptions-bind.htm file.

  • Open this HTML file in a browser.

  • selectedTutorials is an array to store the selected options.

knockoutjs_declarative_bindings.htm
Advertisements