Reputation: 9086
I have this HTML:
<style>
div.icons {
background-color:red;
width:100px;
height:100px;
float:left;
margin-right:10px;
}
</style>
<div class="icons"><input type="checkbox" checked="checked" />Box 1</div>
<div class="icons"><input type="checkbox" checked="checked" />Box 2</div>
<div class="icons"><input type="checkbox" checked="checked" />Box 3</div>
And this JQuery...
<script>
$(document).ready(function() {
$("div.icons").click(
function(){
if ($(this).children("input").is(":checked")) {
$(this).css("background-color","yellow");
$(this).children("input").attr('checked', false);
} else {
$(this).css("background-color","red");
$(this).children("input").attr('checked', true);
}
}
);
});
</script>
When I click on a div, jquery changes the background color of the div and unchecks the input inside of it. But when I click on an input checkbox inside of the div, it doesn't check the input box.
Is there a way to override the $("div.icons").click
when the checkbox is clicked? Or is there a better way to do this?
Upvotes: 0
Views: 4925
Reputation: 675
Here is another way to override the jQuery click event:
$('div').unbind('click').on('click', '.icons', function (event) {
event.stopPropagation();
});
it worked for me.
Upvotes: 4
Reputation: 39872
I would do it something like this. I think the code is far simpler.
div.icons {
background-color:red;
width:100px;
height:100px;
float:left;
margin-right:10px;
}
div.checked {
background: yellow;
}
$('input').click( function(e) {
$(this).parent().toggleClass('checked');
e.stopPropagation();
});
$('div').click( function() {
$(this).children('input').trigger('click');
});
Upvotes: 4
Reputation: 76003
Yeah if you add event.stopPropagation()
to a click
event handler for the check-box elements you can stop the click
event from bubbling up the the check-box's parents:
$('.icons').children().on('click', function (event) {
event.stopPropagation();
});
Upvotes: 4