KnockoutJS - Disable Binding



This binding is the negation of enable binding. This binding disables the associated DOM element when the parameter evaluates to true.

Syntax

disable: <binding-value>

Parameters

  • Parameter consists of Boolean like value, which decides whether the element should be disabled or not. If the parameter is true or true-like value, then the element is disabled.

  • Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value and Integer and non-null objects are considered as true-like value.

  • If the condition in parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be disabled based on the condition result.

Example

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

<!DOCTYPE html>
   <head>
      <title>KnockoutJS Disable Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p> Enter your feedback here:<br><br>
         <textarea rows = 5 data-bind = "value: hasFeedback, 
            valueUpdate: 'afterkeydown'" ></textarea>
      </p>
      
      <p><button data-bind = "disable: !(hasFeedback())">Save Feedback</button></p>

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

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

  • Open this HTML file in a browser.

  • The save button is disabled when the user has not entered any feedback.

You can also use a random expression to decide whether element should be disabled or not.

knockoutjs_declarative_bindings.htm
Advertisements