Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript: Clicking a wrapper element but not a child element
    primarykey
    data
    text
    <p>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). </p> <p><a href="http://jsfiddle.net/misbehavens/WV7sp/" rel="noreferrer">Here's a demo.</a></p> <p>Here's the code:</p> <pre><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); } }); </code></pre> <p>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?</p> <h2>Solution:</h2> <p>Thanks to jAndy's comment for showing how this can be done by checking the event.target property:</p> <pre><code>$('.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); } }); </code></pre> <p>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. <a href="http://jsfiddle.net/misbehavens/cuhwE/" rel="noreferrer">Demo</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload