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
javascript jquery
Andrew
source share