3
votes

I would like to have a checkbox bound with knockout so that when I click on the surrounding div it selects the checkbox.

Below is what I'm after, but the click event only works when you click the div (not the checkbox). I think that this is because both the click and the actual checkbox selection event are occurring.

<div class="checkbox-row" data-bind="click: toggleSelected">
    <input type="checkbox" data-bind="checked: selected" />
    <div data-bind="text: title"></div>
</div>

ko.applyBindings(new (function () {
    var self = this;
    self.title = ko.observable('some text');
    self.selected = ko.observable(false);
    self.toggleSelected = function() {
        self.selected(!self.selected());
        return false;
    };
}));

This is similar to the following question: Knockout - How to bind outer container css from set of checkboxes?

However the solution proposed is to wrap the checkbox and content in a label, which works but I dont want to do this as i have quite a bit of content to fit in the row and a label is quite restrictive.

Is there an alternative way to create this behavior?

http://jsfiddle.net/BgFe9/

1
What is the problem with your current solution? Your fiddle seems to work fine... - nemesv
@nemesv click on the actual checkbox, ive updated the question too - Not loved
I know a solution but it is not nice: you need an empty click binding on the checkbox and set the clickBubble: false : jsfiddle.net/pJuM5 - nemesv
@nemesv thanks that's a better solution than using a label, its workable even if its not tidy. I'm still really keen to know if anyone has a tidier one. You should post it as an answer. - Not loved

1 Answers

1
votes

One possible workaround (which is not too nice) is to define an "empty" click binding on the checkbox and set the clickBubble: false.

This will prevent the calling of the toggleSelected method when clicking directly on the checkbox:

<input type="checkbox" data-bind="checked: selected, 
                                  click: function() { return true; }, 
                                  clickBubble: false" />

Demo JSFiddle.