javascript - JS / jQuery - Filtering divs with checkboxes -
i'm trying filter divs checkboxes using following code:
$("#filtercontrols :checkbox").click(function() { $(".sectioncontent").hide(); $("#filtercontrols :checkbox:checked").each(function() { $("." + $(this).val()).show(); }); if($("#filtercontrols :checkbox").prop('checked') == false){ $(".sectioncontent").show(); } });
this works fine when check first checkbox, filters others when have first checkbox selected. it's hard explain try jsfiddle: http://jsfiddle.net/by9jl/
i don't want rely on having first checkbox checked, there way around this?
try
var sections = $('.sectioncontent'); function updatecontentvisibility(){ var checked = $("#filtercontrols :checkbox:checked"); if(checked.length){ sections.hide(); checked.each(function(){ $("." + $(this).val()).show(); }); } else { sections.show(); } } $("#filtercontrols :checkbox").click(updatecontentvisibility); updatecontentvisibility();
demo: fiddle
Comments
Post a Comment