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 BindingKnockoutJS TextInput Binding >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .