JQuery filtering by checkbox
by carl_marie
HTML
<!-- JavaScript setting start-->
<script>
// Entry every filtering class below.
var $chkbxFilter_tags =['living','legs','black'];
// Entry the block element that will be filtered below.
var $chkbxFilter_blocks = ['section']
</script>
<!-- JavaScript setting end -->
<h1>Filtering the block elements by checkboxes</h1>
<!-- checkbox start -->
<div id="select">
<!-- show all -->
<label class="selected"><input type="radio" id="all" checked="checked">ALL</label>
<!-- Set the filtering class as id="foo" -->
<label><input type="checkbox" id="living" class="sort">living</label>
<label><input type="checkbox" id="legs" class="sort">has legs</label>
<label><input type="checkbox" id="black" class="sort">black</label>
</div>
<!-- checkbox end -->
<!-- filtered start -->
<div id="result">
<!-- Set the filtering class as class="foo" -->
<section class="living">
<p>SNAKE -- class="living"</p>
</section>
<section class="legs">
<p>CHAIR -- class="legs"</p>
</section>
<section class="black">
<p>CHARCOAL -- class="black"</p>
</section>
<section class="living legs">
<p>SQUIRREL -- class="living legs"</p>
</section>
<section class="living black">
<p>SEA URCHIN -- class="living black"</p>
</section>
<section class="legs black">
<p>PIANO -- class="legs black"</p>
</section>
<section class="living legs black">
<p>GNU -- class="living legs black"</p>
</section>
<section class="white">
<p>PAPER -- class="white"</p>
</section>
</div>
<!-- filtered end -->
CSS
/* ---------- required CSS start ------------ */
#result [class*="hidden-"] {display: none;}
/* ---------- required CSS end ------------ */
/* option */
body{font-size: 12px;}
#select {margin-bottom: 1em;}
#result section{border: 1px solid #888; padding: 5px;}
#result section p{margin: 0px;}
#select label.selected {background-color: #fcc;} /* selected */
JavaScript
$(function (){
var $chkbxFilter_all = $('#all');
//When you click "ALL", the other checkboxes turn off.
$chkbxFilter_all.click(function() {
$(".sort").prop('checked',false);
$chkbxFilter_all.prop('checked',true);
});
//The action when the checkboxes is clicked.
$("#select label input").click(function() {
$(this).parent().toggleClass("selected");
$.each($chkbxFilter_tags, function() {
if($('#' + this).is(':checked')) {
$("#result " + $chkbxFilter_blocks + ":not(." + this + ")").addClass('hidden-not-' + this);
$chkbxFilter_all.prop('checked',false).parent().removeClass("selected");
}
else if($('#' + this).not(':checked')) {
$("#result " + $chkbxFilter_blocks + ":not(." + this + ")").removeClass('hidden-not-' + this);
}
});
//If all checkboxes is not selected, add class="selected" to "ALL".
if ($('.sort:checked').length == 0 ){
$chkbxFilter_all.prop('checked',true).parent().addClass("selected");
$(".sort").parent().removeClass("selected");
};
});
});