Herr Kater
Herr Kater

Reputation: 3292

Uncheck radio button with KnockoutJS

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);
    }
};

Fiddle

There is similar question, however the accepted solution has the same issue as mine. link

Upvotes: 1

Views: 1122

Answers (1)

Herr Kater
Herr Kater

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.

fiddle

Upvotes: 1

Related Questions