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