Alex Rivera | Logout

Javascript: Clicking a wrapper element but not a child element

Asked 2011-08-03T17:32:25.990
9

I am writing some javascript (jQuery) that enables a div wrapped around a checkbox, when clicked, will toggle the checkbox element. However, the problem I'm running into is that when you click on the checkbox, it doesn't work because it's being toggled twice (at least I think that's what's happening).

Here's a demo.

Here's the code:

$('.checkbox-wrapper').click(function(){
    var $checkbox = $(this).find('input[type="checkbox"]');
    if ($checkbox.is(':checked')) {
        $checkbox.attr('checked', false);
    } else {
        $checkbox.attr('checked', true);
    }
});

How can I make it so that clicking the checkbox works as normal, but if you click in the surrounding area, it toggles the checkbox?

Solution:

Thanks to jAndy's comment for showing how this can be done by checking the event.target property:

$('.checkbox-wrapper').click(function(e){
    if( e.target.nodeName === 'INPUT' ) {
        e.stopPropagation();
        return;
    }
    
    var $checkbox = $(this).find('input[type="checkbox"]');
    if ($checkbox.is(':checked')) {
        $checkbox.attr('checked', false);
    } else {
        $checkbox.attr('checked', true);
    }
});

And as others have pointed out, this may not be the best example since you get the same functionality (without needing javascript) by wrapping the checkbox with a label tag instead of a div tag. Demo

Edit
Report

3 Answers

2

Try this

$('.checkbox-wrapper').click(function(e){
   if(!$(e.target).is(":checkbox")){
     var $checkbox = $(this).find('input[type="checkbox"]');
     if ($checkbox.is(':checked')) {
         $checkbox.attr('checked', false);
     } else {
         $checkbox.attr('checked', true);
     }
   }
});
answered 2011-08-03T17:37:23.050
1

Try just wrapping a <label> around it.

answered 2011-08-03T17:58:48.623
0

it sounds like you've not stopped the event bubbling up to the parent elements

How to stop event bubbling on checkbox click

answered 2011-08-03T17:39:48.793

Your Answer