Reputation: 3292
I would like to implement a checklist control where only one item can be selected at a time. Basically like a radio button group, the only difference is the items can be unchecked. I created a custom binding to achieve this, it "works" in terms of unchecking the radio button, however the value in the viewmodel doesn't get set to null.
ko.bindingHandlers.radioCheckbox =
{
init: function (element, valueAccessor, allBindings) {
ko.bindingHandlers.value.init(element, valueAccessor, allBindings);
},
update: function (element, valueAccessor, allBindings) {
(function (element, valueAccessor, allBindings) {
$(element).mousedown(function(e) {
e.preventDefault();
if ($(this).is(':checked')) {
allBindings().checked(null);
} else {
$(this).prop('checked', true);
}
}).click(function(e) {
e.preventDefault();
});
})(element, valueAccessor, allBindings);
}
};
There is similar question, however the accepted solution has the same issue as mine. link
Upvotes: 1
Views: 1122
Reputation: 3292
I managed to fix the second solution. I simply changed the select function:
select: function(data) {
if(this.selectedAdmin()==data.id){
this.selectedAdmin(null);
}else{
this.selectedAdmin(data.id);
}
return true;
}
Please note that this is now setting the value to null.
Upvotes: 1