Mihai Dabiste
Mihai Dabiste

Reputation: 157

Knockout checkbox issue

I have a checkbox on which I want to bind a function that does something if the checkbox is checked and something if the checkbox isn't checked.

But the checkbox won't stay checked. It is checked when the function is called, but it gets unchecked after exiting the function. What am I doing wrong?

Here's a sample of what I'm trying to do: http://jsfiddle.net/GSeFD/

JS:

function MyViewModel() {
    var self = this;
    self.click = function(data,event) {
        if ($('#checkbox').is(':checked')){
            console.log('checked');
        }
        else{
            console.log('unchecked');
        }
    }
}
ko.applyBindings(new MyViewModel());

HTML:

<input type="checkbox" id="checkbox" data-bind="click: $root.click" />

Upvotes: 4

Views: 489

Answers (1)

nemesv
nemesv

Reputation: 139808

In a click handler you need to return true if you want to trigger the default browser event (e.g checking the checkbox)

self.click = function(data,event) {
    if ($('#checkbox').is(':checked')){
        console.log('checked');
    }
    else{
        console.log('unchecked');
    }
    return true;
}

Demo JSFiddle.

See also the documentation: Note 3: Allowing the default click action

By the way should also consider to use the checked binding if you are working with check-boxes.

Upvotes: 4

Related Questions