Reputation: 426
I'm trying to enable a button after check a checkbox, the elements are in a modal. I'm using MVC, and I'm adding the observables after the main binding for use them just with the modal like this
<script type="text/javascript">
var Model = function () {
self.check = ko.observable(false);
};
$(document).ready(function () {
ko.cleanNode($('#Modal')[0]);
ko.applyBindings(Model, $('#Modal')[0]);
});
</script>
The html elements inside the modal look like this:
<input type="checkbox" data-bind="checked:viewModel.check">bla bla..
<button type="button" data-bind="enable:viewModel.check==true" class="btn btn-primary">Delete</button>
when I select the checkbox the viewModel.check is true and when is not checked is false which is working fine but the button is always disable. Any advise please
Upvotes: 0
Views: 993
Reputation: 2096
Several issues...
When calling ko.applyBindings
, the first argument needs to be a viewModel instance. This means you need to call new
on your viewModel "class."
ko.applyBindings(new Model())
You are referencing a viewModel
variable which does not exist. When you apply bindings, it uses the scope of the viewModel passed to in to create the binding context. This means that the values available to you in the HTML are the same as those on this
in your viewModel. So, just use check
.
enable
binding bound to expression, not observableThe enable binding must be bound to an observable, but you have bound it to the expression check==true
. In this case, check
is actually an observable — this.check = ko.observable()
, so what you're ultimately comparing is something to the effect of function() { return true } == true
, which is expectedly false
. To do comparisons on observables, you must first unwrap them by calling them as a function: check() == true
. Note, however, that anytime you're writing == true
, you probably don't need to: enable: check
is what you ultimately want.
Upvotes: 2