KnockoutJS Enable/Disable Bindings

The last article covered enable and disabled binding. This article explains another type of form field binding i.e. KnockoutJS Enable/Disable Bindings. Basically what these bindings do is that they enable or disable associated html element depending upon the value they have. If enable has some true-like value for an associated HTML element, the element shall be displayed. Similarly, if an element has some false-like value for enable binding the elment is disabled. The disable binding is mirror opposite of the enable binding. If disable has some false-like value, the associated HTML element is disabled. Similarly, having a false-like value for enable means that the element is enabled. The following sections contain examples for KnockoutJS enable/disable bindings.

KnockoutJS Enable Binding

Take a look at the following code to see knockoutJS enable binding in action.

The above code is extremely interesting. In the HTML view, we have a text area which is bind to “hasMessage” parameter of the StudentModel. This hasMessage parameter is also set as value for the enable binding of the button in the html view. Initially hasMessage parameter is empty string with no value. The enable binding considers an empty string as false-like value. Therefore, when you initially open the page in the browser, you will see that the button is not enabled. However, once you enter some text in the text area, the valueUpdate event is fired and the value for hasMessage parameter is updated to what we have in the text area. For enable binding of the button, now hasMessage parameter is not empty, it has some value. Which means that hasMessage has now become a parameter with “true-like” value, therefore the button “Send Message” is enabled.

Now if you open the above page in browser, you will see the reverse behavior as compared to the last example. By default the button will be enabled. However, if you enter some text, the button becomes disabled.