seePatCode
seePatCode

Reputation: 472

Change checkbox value on parent div click

I'm using knockout and trying to change the value of a checkbox when I click on the parent div. This works great but now I can't change the checkbox value when actually clicking on the checkbox...the span after the checkbox is for debugging purposes to see what the variable is set to. I tried using clickBubble: false but that didn't seem to help either.

I have the following mapping:

var mapping = {
        'teams': {
            create: function(options) {
                options.data.active=ko.observable(false);
                options.data.flipActive= function(team, event){
                    if(!$(event.target).hasClass('team_checkbox'))
                        team.active(!team.active());
                }
                return options.data;
            }
        }
    }

And the following HTML:

            <div id="selectTeamsArea" data-bind="foreach: teams">
                <div class="teams_result_data" data-bind="click: flipActive, clickBubble: false">
                    <img class="floatLeft" height="40" width="40" data-bind="attr: {src: searchImgLink}" >
                    <div>
                        <p data-bind="text: searchBoldName"></p>
                        <p data-bind="text: searchThirdLine"></p>
                    </div>
                    <input class="right team_checkbox" type="checkbox" name="teams" data-bind="value: idString, checked: active, clickBubble: false" />
                    <span data-bind="text: active"></span>
                </div>
                <div class="clear"></div>
            </div>

Any help is greatly appreciated.

UPDATE, INCLUDED JSFIDDLE: http://jsfiddle.net/YYUed/

^Even if you comment out the innards of the "flipActive" the checkbox doesn't work right.

Upvotes: 2

Views: 968

Answers (1)

bdesham
bdesham

Reputation: 16089

I think the best way to do this would be to replace your <div> with a <label>, with the <input> (still) as a child element of the <label>. That approach is not only more semantic and accessible but it has the advantage that clicking on the <label> will be effectively the same as clicking on the checkbox itself.

Upvotes: 3

Related Questions