Reputation: 1779
I have the following approximate HTML:
<div class="productDiv"><div class="someClass><div><input type="checkbox" class="product"/></div></div></div>
<div class="productDiv"><div class="someClass><div><input type="checkbox" class="product"/></div></div></div>
etc.
I am trying to toggle view between all products and only selected products. The view is the parent div, and the checked product checkbox is a few div's deep. What's the best way to show the parent based on a child's checked state, please?
here's my Jquery which is not working.
$('.productDiv').hide().filter('.product:input:checked').show();
Thanks!
Upvotes: 0
Views: 551
Reputation: 104775
Create the change event, then trigger the change event:
$(".product").change(function() {
this.checked ? $(this).parents(".productDiv").show() : $(this).parents(".productDiv").hide();
}).change();
Upvotes: 1
Reputation: 3281
$('input:checkbox .product').each(function(){
if(!($(this).is(':checked'))){
$(this).closest('.productDiv').hide();
}
});
Upvotes: 0
Reputation: 1627
I propose you use the next() selector with the toggle() action. Like that:
$('.product').next().hide();
$('.product').change(function(){
$(this).next().toggle();
});
Here is the full fiddle.
Upvotes: 0
Reputation: 58432
you can achieve what you want by using the following jquery:
$('.productDiv').hide().filter(function() {
return $(this).find('input.product:checked').length > 0;
}).show();
http://jsfiddle.net/peteng/PNySd/
Upvotes: 0
Reputation: 10216
Select all checked inputs and then go up the dom tree to their parent:
$('.productDiv').hide();
$('.product:input:checked').parents('.productDiv').show();
Upvotes: 1