KnockoutJS - Submit Binding



This binding is used to invoke a JavaScript function when the associated DOM element is submitted. This binding is used mostly for form elements.

The form is not actually submitted to the server when submit binding is used. KO prevents browsers default action. If you want submit binding to work as real submit element, then return true from your handler function.

Syntax

submit: <binding-function>

Parameters

  • The binding function here will be the main function which needs to be invoked after submit event.

  • This function can be any JavaScript function and need not be necessarily ViewModel function.

Example

Let us take a look at the following example which demonstrates the use of submit binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Submit Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <form data-bind = "submit: addition">
         <p>Enter first number: <input data-bind = "value: var1" /></p>
         <p>Enter second number: <input data-bind = "value: var2" /></p>
         <p><button type = "submit" >Click here for addition</button></p>
      </form>

      <script type = "text/javascript">
         function ViewModel () {
            self = this;
            self.var1 = ko.observable(10);
            self.var2 = ko.observable(30);
            self.var3 = ko.observable(0);

            this.addition = function() {
               self.var1(Number(self.var1()));
               self.var2(Number(self.var2()));

               this.var3 = self.var1() + self.var2();
               alert("Addition is = "+ this.var3 );
            };
         };

         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 submit-bind.htm file.

  • Open this HTML file in a browser.

  • This program adds 2 numbers. In KO, any accepted data from UI is considered in String format by default, so it needs to be converted to Number format in case of Numeric operation.

Please refer to click binding for additional notes such as passing extra parameters, etc. All notes on that page also apply to submit binding.

knockoutjs_declarative_bindings.htm
Advertisements