Using filters to clear other filters not clearing checked state

Hello!

Hoping someone would be able to help me out here. I am working on a script for some advanced filtering functionality.

When a user selects category filter I need it to clear all other filters (except the category selected) and then when a user selects a subcategory filter I need it to ONLY clear the category filter, but keep all others. That way a user can only filter by subcategories within a singular category.

I am really close, but I cannot get either of my scripts to uncheck the radio and checkboxes. I can only get it to clear the _active class on the filters. There are a couple different approaches here, none seem to work.

There might even be a more elegant way of accomplishing what I am trying to do here, this is what I have.

Thanks!


<!-- Category Filter Field Clears ALL except the Category selected -->
<script>
  // Ensure the CMS filter instance is loaded and accessible
  window.fsAttributes = window.fsAttributes || [];
  window.fsAttributes.push([
    'cmsfilter',
    (filterInstances) => {
      console.log('cmsfilter Successfully loaded!');

      // Access the first CMSFilters instance on the page
            const [filterInstance] = filterInstances;

            function checkAndUncheck() {
              // Get all checkboxes in the form
              const checkboxes = document.querySelectorAll('#filterServiceList input[type="checkbox"]');
              checkboxes.forEach((checkbox) => {
                if (checkbox.checked) {
                  // If the checkbox is checked, uncheck it
                  checkbox.checked = false;
                } else {
                }
              });
            }

// Add event listeners to category filter elements (radio)
      document.querySelectorAll('[fs-cmsfilter-field="category"]').forEach((item) => {
        item.addEventListener('click', () => {
    
          // Define the category filter key and value
          const categoryFilterKey = 'category';
          const categoryFilterValue = item.getAttribute('fs-cmsfilter-field');

        // Clear filter values for all filters
          filterInstance.filtersData.forEach((filter) => {
            // Clear the all filters and remove the active class from filter labels
              filter.values.clear();
              filter.elements.forEach((element) => {
                const activeElement = element.element.closest('.fs-cmsfilter_active');

                if (activeElement) {
                  checkAndUncheck();
                  activeElement.classList.remove('fs-cmsfilter_active');
                }
              });

            // Reset category filter
            if (filter.filterKeys.includes(categoryFilterKey)) {
              filter.values.clear();
              filter.values.add(categoryFilterValue);
            }
          });
        });
      });
    },
  ]);
</script>


<!-- Subcategory Filter (Clears Category Only) -->
<script>
  // Ensure the CMS filter instance is loaded and accessible
  window.fsAttributes = window.fsAttributes || [];
  window.fsAttributes.push([
    'cmsfilter',
    (filterInstances) => {
      console.log('cmsfilter Successfully loaded!');

      // Access the first CMSFilters instance on the page
      const [filterInstance] = filterInstances;

      // Function to clear only Category filters
      function clearCategoryFilters() {
        const categoryFilterKey = 'category';
        
        filterInstance.filtersData.forEach((filter) => {
          if (filter.filterKeys.includes(categoryFilterKey)) {
            // Clear category filter values
            filter.values.clear();

            // Iterate over each category filter element and uncheck any selected radio button
            filter.elements.forEach((element) => {
              const activeElement = element.element.closest('.fs-cmsfilter_active');
              if (activeElement) {
                activeElement.classList.remove('fs-cmsfilter_active');
              }
              const radioButton = element.element.querySelector('input[type="radio"]');
              if (radioButton) {
                radioButton.checked = false;
              }
            });
          }
        });
      }

      // Add event listeners to subcategory filter elements (checkboxes)
      document.querySelectorAll('[fs-cmsfilter-field="subcategory"]').forEach((item) => {
        item.addEventListener('click', () => {
          const subcategoryValue = item.getAttribute('fs-cmsfilter-value');

          // Clear category filters before applying the subcategory filter
          clearCategoryFilters();

          // Apply the subcategory filter by setting the value in the existing filter instance
          filterInstance.setFilterValues({
            subcategory: [subcategoryValue], // Ensure only 'subcategory' values are set
          });

          // Trigger a re-render to ensure the UI updates immediately
          filterInstance.listInstance.update();
        });
      });
    },
  ]);
</script>

Share link (please ignore the messiness, I’m just testing functionality)

Hey @bree! The CMS Filter API includes a built-in method for programmatically clearing filters:

  /**
  * Resets the active filters.
  * @param filterKeys If passed, only this filter key will be reset.
  * @param value If passed, only that specific value and the elements that hold it will be cleared.
  */
  resetFilters(filterKeys?: string[], value?: string): Promise<void>;

For example, if a user selects a subcategory filter and you only want to clear the main category filter, you can use:

await fsAttributes.filter.resetFilters(["category"]);

This method is asynchronous, so using await ensures the filters are fully reset before proceeding with other logic.

It also automatically handles unchecking any associated checkboxes or radio buttons in the filter UI so you won’t have to worry about it :wink:

If you need help with the implementation please share a live link and I can help set it up :muscle:

Thank you @Support-Luis this seems to have worked pretty well!

If I click around really quickly or leave the page open with a category filter selected it will trip up and won’t remove a filter before applying the next, if you have any suggests on how I can refine from here I would love to hear it, otherwise thank you again!

Share Link

Hey @bree! Could you please DM me the password for the live site? I’ll take a look and see what I can do :wink:

1 Like

@Support-Luis sent you a chat, thank you!

1 Like