Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout checkbox selection based on parent div

Tags:

knockout.js

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/

like image 817
Not loved Avatar asked Feb 05 '26 08:02

Not loved


1 Answers

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.

like image 56
nemesv Avatar answered Feb 08 '26 23:02

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!