'Knockout enable binding not working
I can't get the enable binding to work in Knockout JS. With the enabled property set to false, the button is not disabled and I can still click it.
see fiddle
<a class="btn btn-xl btn-primary"
href="#"
role="button"
data-bind="enable: enabled, click: clicked, visible: isVisible">
<i class="icon-only icon-ok bigger-130"></i>
</a>
var ViewModel = function(){
var self = this;
self.enabled = ko.observable(false);
self.isVisible = ko.observable(true);
self.clicked = function(){
alert('You clicked the button');
};
};
$(function(){
var model = new ViewModel();
ko.applyBindings(model);
})
Solution 1:[1]
Enable binding does not work with anything you want.
This is useful with form elements like input, select, and textarea It also works with buttons. Like in my example http://jsfiddle.net/5CbnH/1/
But it does not work with your link. You are using twitter bootstrap and they enable/disable their "buttons" with css classes. So you have to use css binding like this:
data-bind="css: { yourClass: enabled }"
Check what class is responsible in bootstrap for showing your "button" and modify your code accordingly with css binding.
Solution 2:[2]
Right:
? enable
? disable
Wrong:
? enabled
? disabled
Make sure you use disable
instead of disabled
and enable
instead of enabled
.
<input type="text" data-bind="value: foo, enable: isEditing"/> YES!!
<input type="text" data-bind="value: foo, enabled: isEditing"/> NO!
Easy mistake to make :-)
Solution 3:[3]
For people who might find this in a search:
I had a problem getting the enable binding to work as well. My problem was trying to use a complex expression without referencing the observables like functions:
<input type="button" data-bind="enable:AreAllStepsVerified && IsFormEnabled, click:SubmitViewModel"/>
Should have been:
<input type="button" data-bind="enable:AreAllStepsVerified() && IsFormEnabled(), click:SubmitViewModel"/>
Solution 4:[4]
What Salvador said in his answer.
You must understand that the enabled
and disabled
binding in knockout work by putting a disabled
attribute on the target DOM element. Now if you look at the HTML documentation you'd notice that not all HTML element support this attribute.
Actually only form elements (e.g. <button>
) do. <a>
does not.
Solution 5:[5]
I got it to work by changing the anchor tag to a button, not really sure why this makes it work, but it works nonetheless.
Updated fiddle.
<button class="btn btn-xl btn-primary"
role="button"
data-bind="enable: enabled, click: clicked, visible: isVisible">
<i class="icon-only icon-ok bigger-130"></i>
</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joel Cochran |
Solution 2 | |
Solution 3 | Community |
Solution 4 | jods |
Solution 5 | Th4t Guy |