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

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 Binding

In the previous article, we saw how can we bind value of a form field with a property in an object model. In this article we shall explain knockoutJS textInput binding. TextInput binding is one of the most simplest type of Knockout bindings. It binding binds the HTML DOM input element’s property with the object’s property in the view model. The difference between textInput and value binding is that the former can be used on every input type such as drag and drop, clip board events and auto complete while latter is used with form fields like input, text area and select.

Now if you try to change the textInput attribute of the form field, the value of the corresponding object model property bound with the field’s textInput attribute shall also be updated. Similarly, updating the property in the model shall updating the value of the textInput attribute of form field. Take a look at the following example to see knockoutJS textInput binding in action

KnockoutJS TextInput Binding

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

<body>
    

   <p>Student Name: <input data-bind="textInput: StudentName" /></p>
   <p>Student  <strong data-bind="text: StudentName"></strong> obtained 90% marks.</p>

   <script>

   function StudentModel() {
       this.StudentName = ko.observable("");
   }

  
   ko.applyBindings(new StudentModel());
   </script>
    
</body>
</html>

Download the code Try the code

Let’s start from the paragraph tag at the top. Inside the paragraph we have the input element. The data-bind attribute here binds the textinput attribute entered in this input tag to the “StudentName” property of the StudentModel view model. Next again data-bind binds the value of the StudentName attribute to “text” attribute of the paragraph. Now if you enter any name in the text box and press the enter key. The corresponding value in the paragraph shall be updated immediately. This is because we have used “observable” with StudentName.

Now come to the script section. Here we create a ViewModel named StudentMode. StudentModel has one attribute StudentName. The ko.observable is called on “StudentName” to change it to observable property. Therefore, this “observable” keeps an eye on “StudentName”. Thus whenever value for StudentName is updated anywhere, it is updated through out the application.

KnockoutJS Value Binding

KnockoutJS value binding is one of the most simplest type of Knockout bindings. Value binding binds the HTML DOM element’s value property with the object’s property in the view model. The value binding is commonly used with form fields like input, text area and select. Now if you try to change the value of the form field, the value of the corresponding object model property bound with the field’s value shall also be updated. Similarly, updating the property in the model shall updating the value of the form field. Take a look at the following example to see value binding in action.

KnockoutJS Value 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>Student First Name: <input data-bind="value: StudentFName" /></p>
  <p>Student Last Name: <input data-bind="value: StudentLName" /></p>
   <p>Student  <strong data-bind="text: StudentFullName"></strong> obtained 90% marks.</p>

   <script>

   function StudentModel() {
     this.StudentFName = ko.observable('');
     this.StudentLName = ko.observable('');
     this.StudentFullName = ko.computed(function() {
        return this.StudentFName() + " " + this.StudentLName();
    }, this);
   }
       
       

  
   ko.applyBindings(new StudentModel());
   </script>
    
</body>
</html>

Download the code Try the code

In the above code in html view, we have to input boxes one for the first name and the second for the last name. The data-bind attribute binds the value attribute of the first input box to the StudentFName property of the object model. Similarly, The data-bind attribute binds the value attribute of the second input box to the StudentLName property of the object model. In the paragraph, the text property is bind to “StudentFullName”.

Now if you come down to the JavaScript view model. You should see a StudentModel with three member variables. StudentFName, StudentLName and StudentFullName. Here the first two variables are assigned as observable while the last variable is declared computed variable. The knockoutJS computed observable contains a function which basically returns the concatenation of the first two variables.

Now, if you open the above web page in browser, you should see two empty text fields. If you enter anything in the first text field it will be displayed in the bold form in the paragraph tag below. Similarly, if you enter anything in the second text field. It will appear appended after the text in the first text field inside the paragraph below. Updating the first name or last name shall also update the computed full name. This shows that updating the value from the form field, updates the property that is bound with those form fields and vice versa.

KnockoutJS Focus Binding

Till now, we have covered most of the form field bindings. We studied, click binding, event bindings, if/ifnot binding and enable/disabled binding etc. In this article we shall study another type of binding i.e KnockoutJS Focus Binding. This type of binding binds a focus-able HTML DOM elements such as a text field or a button with a javascript view model parameter. The binding is two way. If the HTML element is focused, the corresponding view model parameter is assigned a true. Similarly, if in the code, the view-model parameter has a false value, the associated HTML element is de-focused. KnockoutJS focus binding is extremely useful in scenarios where form elements are dynamically generated and you want to set default focus to one of the form field. Take a look at the following example to see KnockoutJS Focus binding in action.

KnockoutJS Focus Binding Example

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

<body>
    

    <label><input type="checkbox" data-bind="checked: Male" /> Male</label>
 
<div data-bind="if: Male">Student is a Male.</div>
    
    
<script>
    function StudentModel() {
    this.Male = false;
}

ko.applyBindings(new StudentModel());
    
</script>
    
</body>
</html>

Download the code Try the code

Take a careful look at the above piece of code. It contains a text box with a binding “hasFocus.” This is how you add focus to the element. The value for this binding can be true or false. In the above code we bind the focus of this text box with StudentModel parameter “hasFocus.” The value of “hasFocus” parameter is set to false by defult. Next in on the click event of the button in HTML view, we call the setFocus method of javascript. The setFocus function basically sets the value of hasFocus parameter to true.

Now open the above page, in the browser. You should see a text-box and button. By default the focus is at somewhere else. However if you click button, the “setFocus” function executes which sets the value of “hasFocus javaScript variable to true. Therefore the textbox becomes focused and the statement after the button becomes visible.”

KnockoutJS Checked Binding

We covered enabled and disabled binding in the last article. This article explains another very important type of binding i.e. knockoutJS checked binding. This time of binding binds the check-able HTML dom elements such as checkboxes and radiobuttons with the view model properties. It is important to note that the binding is two way. Checking a check box or radio button sets the value of the corresponding view-model parameter to true. Similarly, if you set the value of the parameter to false in the view model, it un-checks the corresponding HTML element. It is important to mention here that for HTML elements that are non-checkable, you should value-binding to set and retrieve values. Now, take a look at a very simple example of checked binding.

KnockoutJS Checked Binding Example

Take a very carefulllook at the following example to see knockoutJS checked bining in action.


Download the code Try the code

In the above code we have check box and a div in html view section. In the javascript view model section we create model named StudentModel with one parameter i.e. Male. The value assigned to Male is true by default. Now come back to view section, here we set the “checked” attribute of the check box to the value of Male parameter which is true. Therefore, when you open the page in the browser, you shall see Male checkbox checked. Secondly, the div contains an if binding which says that display the div only if Male parameter is set to true. When you open the page, the text inside the div shall be visible.

Now in the javaScript view model, change the value of Male parameter to false and open the page. You shall male checkbox unchecked and the contents of the div removed from the page. In the next article, we shall study focus binding.

KnockoutJS Enable/Disable Bindings

The last article covered enable and disabled binding. This article explains another type of form field binding i.e. KnockoutJS Enable/Disable Bindings. Basically what these bindings do is that they enable or disable associated html element depending upon the value they have. If enable has some true-like value for an associated HTML element, the element shall be displayed. Similarly, if an element has some false-like value for enable binding the elment is disabled. The disable binding is mirror opposite of the enable binding. If disable has some false-like value, the associated HTML element is disabled. Similarly, having a false-like value for enable means that the element is enabled. The following sections contain examples for KnockoutJS enable/disable bindings.

KnockoutJS Enable Binding

Take a look at the following code to see knockoutJS enable binding in action.

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

<body>
    
   <p> Enter Message:<br><br>
   <textarea rows=10 data-bind="value: hasMessage, valueUpdate: 'afterkeydown'" ></textarea></p>
   <p><button data-bind="enable: hasMessage">Send Message</button></p>

<script type="text/javascript">
   function StudentModel (){
      hasMessage = ko.observable('');
   };

   var sm = new StudentModel();
   ko.applyBindings(sm);
</script>
    
</body>
</html>

Download the code Try the code

The above code is extremely interesting. In the HTML view, we have a text area which is bind to “hasMessage” parameter of the StudentModel. This hasMessage parameter is also set as value for the enable binding of the button in the html view. Initially hasMessage parameter is empty string with no value. The enable binding considers an empty string as false-like value. Therefore, when you initially open the page in the browser, you will see that the button is not enabled. However, once you enter some text in the text area, the valueUpdate event is fired and the value for hasMessage parameter is updated to what we have in the text area. For enable binding of the button, now hasMessage parameter is not empty, it has some value. Which means that hasMessage has now become a parameter with “true-like” value, therefore the button “Send Message” is enabled.

Now, let’s repeat the above example with knockoutJS disabled binding

KnockoutJS Disable Binding

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

<body>
    
   <p> Enter Message:<br><br>
   <textarea rows=10 data-bind="value: hasMessage, valueUpdate: 'afterkeydown'" ></textarea></p>
   <p><button data-bind="disable: hasMessage">Send Message</button></p>

<script type="text/javascript">
   function StudentModel (){
      hasMessage = ko.observable('');
   };

   var sm = new StudentModel();
   ko.applyBindings(sm);
</script>
    
</body>
</html>

Download the code Try the code

Now if you open the above page in browser, you will see the reverse behavior as compared to the last example. By default the button will be enabled. However, if you enter some text, the button becomes disabled.

KnockoutJS Submit Binding

A couple of articles ago we started our discussion on form field bindings. We saw how to bind html events with view model function and how to handle events. In this article we shall study yet another type of binding i.e. knockoutJS submit binding. Submit binding is simple. Basically it binds the submit event of HTML DOM element with a javaScript function in the view model. Among submit-able HTML elements, form element is mostly widely used.

When the submit event of a form is bind with a view-model function, KnockoutJS makes sure that the form is not submitted to the server, rather only the corresponding JavaScript function executes.

KnockoutJS Submit Binding Example

Take a look at the following piece of code to see Submit binding in action.

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

<body>
    
  <body>

   <form data-bind="submit: sum">
   <p>Enter number 1: <input data-bind="value: num1" /></p>
   <p>Enter number 2: <input data-bind="value: num2" /></p>
   <p><button type="submit" >Click to See Sum</button></p>
   </form>

<script type="text/javascript">
   function StudentModel (){
      self = this;
      self.num1 = ko.observable(5);
      self.num2 = ko.observable(10);
      self.result = ko.observable(0);

      this.sum = function(){
         self.num1(Number(self.num1()));
	     self.num2(Number(self.num2()));

         this.result = self.num1() + self.num2();
		 alert("Sum of numbers is = "+ this.result );
      };
   };

   var sm = new StudentModel();
   ko.applyBindings(sm);
</script>

    
    

    
</body>
</html>

Download the code Try the code

Take a careful look at the above code. In the html view section we have two input fields whose value is bind to to num1 and num2 parameters of StudentModel via data-bind. The submit event of the form is bind with the sum function of the StudentModel. The sum function simply captures the value entered by the user in two input fields, adds the two and display their sum inside an alert box.

Now open the above page in browser, you shall see two text fields, enter any two numbers in the text field and you shall see their sum in the alert box in the output.

It is important here that if want to submit your form to server in normal manner, simply return true from submit binding.

Another important question arises here that why not simple use click event on the form button and handle it in the view model instead of using submit. The answer is that you can do so, but submit also allows you to generate submit event on enter press unlike click.

KnockoutJS Event Binding

In the last article we started studying form-field bindings. We saw click binding with the help of an example. In this article, we shall study yet another type of form-field binding i.e. knockoutJS event binding. In the click binding article we saw how to bind click event on any DOM element with an event handler which was basically a function in JavaScript view model. However there are several other types of event which can also be handled. KnockoutJS event binding basically handles such events. For instance you may want to execute a specific function when user hover mouse over a DOM element or leaves a DOM element. In such cases event binding comes handy.

KnockoutJS Event Binding Example

Take a look at the following code, here we shall execute functions based on user interaction with DOM elements. We shall handle the mouseover and mouseout events.

If binding Example!

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

<body>
    
    <div>
    <div class="yellow" data-bind="event: { mouseover: displayDetails, mouseout: hideDetails }">
        Mouse over me
    </div>
    <div data-bind="visible: messageDetails">
        Details
    </div>
</div>
 
<script type="text/javascript">
    var MessageModel = {
        messageDetails: ko.observable(false),
        displayDetails: function() {
            this.messageDetails(true);
        },
        hideDetails: function() {
            this.messageDetails(false);
        }
    };
    ko.applyBindings(MessageModel);
</script>

    
</body>
</html>

Download the code Try the code

Take a look at the html view section first. Here we have a div which uses event binding to bind the mouseover and mouseout events with event handler functions. See how we can use event binding. Simply specify event inside the data-bind attribute, followed by opening and closing curly brackets. Inside the brackets, specify the event and the corresponding even handler separated by a colon. You can specify multiple events and event handler each pair separated by a comma. Next we in the html view we have div that uses visible binding and will be visible if the messageDetails parameters is set to true.

Now, when you hover mouse over the first div, the mouseover event fires which bound to “displayDetails” function. This function sets messageDetails parameter to true hence the it makes second div visible. Similarly, the second event mouseout calls the “hideDetails” function which sets the “messageDetails” parameter to false thus making the second div invisible

If you open the above page in browser and hover mouse over the div with yellow background you shall see a message appear under it. If you take mouse out of the yellow div,the message shall disappear.

KnockoutJS Click Binding

In the previous articles, we covered appearance and text bindings as well as control flow bindings. From this article onward, we shall see different types of form field bindings. These are the type of bindings that are associated with the behavior of different form fields. In this article we shall study KnockoutJS click binding.

Basically knockoutJS click binding allows us to attach click event of any HTML DOM element to a function or event handler in JavaScript view model. Usually click event for button, links or list items is handled. Take a look at the following example to see click binding in action.

KnockoutJS Click Binding Example

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

<body>
    

    <ul data-bind="foreach: fruits">
    <li>
        <span data-bind="text: $data"></span>
        <button data-bind="click: $parent.removeFruits">Remove Fruit</button>
    </li>
</ul>
 
 <script type="text/javascript">
     function FruitModel() {
         var self = this;
         self.fruits = ko.observableArray(['Apple', 'Orange', 'Banana','Guava', 'Peach']);
 
         // The current item will be passed as the first parameter, so we know which place to remove
         self.removeFruits = function(fruit) {
             self.fruits.remove(fruit)
         }
     }
     ko.applyBindings(new FruitModel());
</script>
    
</body>
</html>

Download the code Try the code

Take a careful look at the above code, lots of things are happening in it. First have a look at the HTML view section. Here we have list which uses foreach binding to iterate over fruits array. Inside the list we have a span tag which displays the name of the fruit and a button tag where we bind the click event of the button to the “removeFruits” function in the view model.

Now come down to the view model. Here we have a FruitModel which contains an observable fruits array with five fruits. Next we have a function “removeFruits” that takes name of a fruit and removes that fruit from the list. At

Now open the page in the browser, here you shall see five fruit names with five buttons. It is very interesting to note here that each button contains the data of the corresponding fruit. For instance if you click the button in front of button, the click event fires and banana is passed to the removeFruits function which removes banana from the fruits array. Since, fruits array is observable the front end or html view is updated immediately banana along with its remove button disappear from the list.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .