Javascript: Clicking on a wrapper element but not a child element

I am writing javascript (jQuery) that allows a div wrapped around a checkbox when clicked will toggle the checkbox item. However, the problem I am facing is that when you click on this checkbox, it doesn’t work because it switches twice (at least I think it happens).

Here is a demo.

Here is 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 the click on the checkbox work fine, but if you click on the surrounding area, it will switch the checkbox?

Decision:

Thanks to jAndy's comment 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 the need for javascript) by wrapping the checkbox with a tag tag instead of a div tag. Demo

+8
javascript jquery
source share
4 answers

Check the event.target property.

The target property can be an element registered for an event or its descendant. It is often useful to compare event.target with this to determine if the event is being processed due to bubbling events.

+5
source share

try it

 $('.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); } } }); 
+2
source share

Try just wrapping a <label> around it.

+1
source share

it looks like you did not stop the event bubbling up to the parent elements

How to stop a bubble event when clicking on a checkbox

0
source share

All Articles