I have the following simplified html:
<div class="foo" style="width:200px; height:200px;">
<input type="checkbox" />
</div>
<script type="text/javascript">
$('.foo').click(function(){$(this).find('input:checkbox')[0].click();});
</script>
Clicking the 200x200 div 'foo' works well, and raises the click event for the checkbox inside it.
However when I exactly click the checkbox itself, it fires its 'normal' event, plus the jquery bound event above, meaning the checkbox checks itself, then unchecks itself again.
Is there a tidy way to prevent this from happening?
How about this: instead of using a div, use a <label>
. It's more semantically correct, does exactly what you want, and requires no JavaScript.
Working example here: http://jsfiddle.net/LhSG9/1/
Events bubble. You would need test the e.target
that was clicked.
And if you're just trying to check/uncheck the box, you should set its checked
property.
$('.foo').click(function( e ){
if( e.target.tagName.toUpperCase() !== 'INPUT' ) {
var cbox = $(this).find('input:checkbox')[0];
cbox.checked = !cbox.checked;
}
});
EDIT: Fixed a couple mistakes.
Working demo: http://jsfiddle.net/LhSG9/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With