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.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .