Hi Team
I have check box for items got price range, the issue is the other selected catetory is not independent it affects other category. For instance when checked box for price range is select and unchecked it also hides instead to function on its own. How can i prevent this from happening?
JavaScript
Filter by price
All Price
1000
R0 - R100
150
R100 - R200
295
R200 - R300
246
R300 - R400
145
R400 - R500
168
$(document).ready(function() {
// Price checkboxes change event
$('input[type=checkbox][id^=price]').change(function() {
var $allCheckbox = $('#price-all');
var $checkedCheckboxes = $('input[type=checkbox][id^=price]:checked');
var $products = $('ul#product-list').find('li');
if ($checkedCheckboxes.length > 0 && !$allCheckbox.is(':checked')) {
$products.hide();
$checkedCheckboxes.each(function() {
var price = $(this).attr('id').split('-')[1];
$products.filter('[data-price="' + price + '"]').show();
});
} else if (!$allCheckbox.is(':checked')) {
$products.hide();
} else {
$products.show();
}
});
// Price all checkbox click event
$("#price-all").click(function() {
if($(this).is(':checked')) {
$(".custom-checkbox .badge").show();
} else {
$(".custom-checkbox .badge").hide();
}
});
});
Naimish MakwanaRank #324 · 7.7K reputationPosted May 8, 2023, 5:45 AM EDT
The issue with the current implementation is that when any of the price range checkboxes are unchecked, it hides all the products that don't match the checked checkboxes including the products that belong to the categories that were selected through other checkboxes.
To prevent this from happening, you need to separate the filtering logic for the price range checkboxes from the logic for other checkboxes. You can achieve this by adding a separate filter function for the price range checkboxes.
Here's an updated JavaScript code that should solve the issue:
$(document).ready(function() { // Function to filter products based on price range checkboxes function filterByPrice() { var $allCheckbox = $('#price-all'); var $checkedCheckboxes = $('input[type=checkbox][id^=price]:checked'); var $products = $('ul#product-list').find('li'); if ($checkedCheckboxes.length > 0 && !$allCheckbox.is(':checked')) { $products.hide(); $checkedCheckboxes.each(function() { var price = $(this).attr('id').split('-')[1]; $products.filter('[data-price="' + price + '"]').show(); }); } else if (!$allCheckbox.is(':checked')) { $products.show(); } } // Function to filter products based on other checkboxes function filterByOther() { // TODO: Add the filtering logic for other checkboxes } // Price checkboxes change event $('input[type=checkbox][id^=price]').change(function() { filterByPrice(); }); // Other checkboxes change event $('input[type=checkbox]:not([id^=price])').change(function() { filterByOther(); }); // Price all checkbox click event $("#price-all").click(function() { if($(this).is(':checked')) { $(".custom-checkbox .badge").show(); } else { $(".custom-checkbox .badge").hide(); } filterByPrice(); }); });Thanks