Reputation: 129
I have a checkbox bound to a viewmodel's observable property, whose value will be Y or N. I want the the checkbox to be checked when the value is Y and unchecked when the value is N. How to achieve this?
I am able to achieve it if the value is 0 or 1 but not on Y and N. What will be the way to achieve the desired behavior on having value Y or N?
The check-box code is as below:
<input type="checkbox" data-bind="checked: job.Open" />
Upvotes: 1
Views: 663
Reputation: 63729
Use a computed writable observable:
var ViewModel = function() {
var self = this;
self.actualObservable = ko.observable('Y');
self.relatedObservable = ko.computed({
read: function() { return self.actualObservable() === 'Y'; },
write: function(x) { self.actualObservable(!!x ? 'Y' : 'N'); }
});
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: relatedObservable"> = Checked<br />
<i data-bind="text: actualObservable"></i> = Actual
You could also just bind the actualObservable
to the checkbox, and make the computed observable read only. IMHO that would usually make more sense, but it depends on your context. That version looks like this:
var ViewModel = function() {
var self = this;
self.actualObservable = ko.observable(true);
self.relatedObservable = ko.computed(function() {
return !!self.actualObservable() ? 'Y' : 'N';
});
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: actualObservable"> = Checked<br />
<i data-bind="text: relatedObservable"></i> = Actual
Upvotes: 1