I am using jQuery to filter product items on a page (hide and display DIVs) I am using filter as a replacement since PHP $_GET is a bit old fashion we're trying to do this via jQuery. I using filter() and data attribute.
How can I turn off the current selection of checkboxes except the existing item? How can I hide the items based off selection and unhide when not?
HTML
<input type="checkbox" id="drama" onClick="filterCategory(this.value)" value="drama" /> Drama<br />
<input type="checkbox" id="romance" onClick="filterCategory(this.value)" value="" /> Romance<br />
<input type="checkbox" id="horror" onClick="filterCategory(this.value)" value="horror" /> Horror<br />
<!--------------------->
<div class="products">
<div class="productItem" data-price="250" data-category="horror">
Scary Book
<div class="productItemPrice"><span>£250</span></div>
</div>
<div class="productItem" data-price="150" data-category="drama">
Drama Poems
<div class="productItemPrice"><span>£150</span></div>
</div>
<div class="productItem" data-price="250" data-category="romance">
Love Story
<div class="productItemPrice"><span>£250</span></div>
</div>
<div class="productItem" data-price="241" data-category="horror">
Creep Book
<div class="productItemPrice"><span>£241</span></div>
</div>
</div>
<!--------------------->
jQUERY
function filterCategory(id) {
var pid=$(".productItem"); // Which product is it
var checkid=$('#'+id); // The name of the checkbox form
var cid=$(pid).data("category"); // The value of the checkbox form
if ($(checkid).is(':checked')){
$(pid).hide().filter(function () {var catId=$(this).data("category");return catId;}).show();
} else {
$(pid).show().filter(function () {var catId=$(this).data("category");return catId;}).show();
}
}
CSS
.productItem{float:left;padding:5px;margin:5px;border:1px solid #eaeaea}
body{font-family:verdana}
JSFiddle
You could try using something like this instead,
Firstly remove the onclick attribute on the checkboxes - use jQuery to bind the click event :
// bind to click
$('input[type="checkbox"]').click(function() {
// any checked
if ($('input[type="checkbox"]:checked').length > 0) {
// hide all
$('.products >div').hide();
// loop checked and display relavent div
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
});
} else {
// none checked - show all
$('.products >div').show();
}
});
来源:https://stackoverflow.com/questions/12563152/jquery-simple-checkbox-to-hide-and-show-divs-product-filtering