lundi 17 août 2020

Using jQuery to disable empty categories in a filtered listing

I am fairly new to Javascript/jQuery. I have a list of items (in this case, course offerings) structured in a UL. Each "course" is an LI element. The list is being filtered by categories using jQuery, which is controlling the visibility of each list item after checking its "data-category" attribute matches the selected category (a checkbox selected by the user).

This is all working great.

I have a further requirement that users should not see "0 results" when selecting a combination of filters/categories. So, I have to check each category will not return an empty set. If it will, I wish to disable that category.

To start, I followed this example: jQuery Isotope filtering: add a class when there are no items in a data-category in the grid

This is the code I came up with:

        // whenever a category is selected, check all categories to see which ones
        // would be empty if selected.
        // To do this, we iterate over all categories, then over all visible items, and check if their data-category contains
        // the category that matches the current category. If 0 items match, disable that category.
        function DisableEmptyCategories() {
            $allCategories = $(".checkboxlist input[type='checkbox']");
            $allCategories.each(function (i, element) {
                var $checkbox = $(element);
                // check if checkbox's value is in any displayed item's data-category tag.
                var val = $checkbox.val();
                if (val !== undefined) {
                    if ($filteredResults.find('[data-category~="' + val + '"]').length == 0) {
                        // if equals 0, disable. 
                        $checkbox.addClass('disabled').attr('disabled', 'disabled');
                    }
                    else {
                        // else, make sure it's enabled.
                        $checkbox.removeClass('disabled').attr('disabled', 'false');
                    }
                }
            });
        }

Unfortunately, the end result is that it disables all of my categories every time, and I cannot figure out why. I have checked that the $filteredResults list is populated correctly as is the val variable. However it seems my .find() isn't working and always returns 0.

Here is a fiddle illustrating the problem: https://jsfiddle.net/yvgx81k4/ In this example, there are items matching all categories except "In-Class", so only the "In-Class" category should be disabled, but all of them get disabled.

What am I doing wrong?




Aucun commentaire:

Enregistrer un commentaire