Display count of each item on page load - CMS Filter

Hi Finsweet team,

I use the CMS Filter (a filter composed of two groups of checkboxes) with fs-cmsfilter-element = “filter-results-count”.

My problem is:
I need to submit a form/filter submission to be able to view the counts of each item.

How can I display the count of items when the page loads?

Here is a Loom.
And here is the read-only link.

Thank you in advance for your help.

Hey @hello14!

Could you give this a try?

<script>
  setTimeout(function () {
    window.fsAttributes = window.fsAttributes || [];
    window.fsAttributes.push([
      'cmsfilter',
      function (filterInstances) {
        console.log('filter loaded!');
        const [filterInstance] = filterInstances;
        const filtersData = filterInstance.filtersData;
        let resultsArray = [];

        filtersData.forEach(function (element) {
          const elements = element.elements;
          elements.forEach(function (element) {
            let filterValue = element.value.trim();
            let resultsNumber = element.resultsCount;
            resultsArray.push({ filterName: filterValue, filterResults: resultsNumber });
          });
        });

        resultsArray.forEach(function (filter) {
          let elements = Array.from(document.querySelectorAll('[fs-cmsfilter-field]')).filter(
            function (element) {
              return element.textContent.trim() === filter.filterName;
            }
          );

          elements.forEach(function (element) {
            let resultsTextElement = element.nextElementSibling ? element.nextElementSibling : null;
            if (resultsTextElement) {
              console.log(resultsTextElement);
              resultsTextElement.textContent = ` (${filter.filterResults})`;
            }
          });
        });
      },
    ]);
  }, 100);
</script>

Hi @Support-Luis,

And thank you for your quick feedback.
It’s working like a charm, thank you!

Have a good day,
Best,

1 Like

Great to hear it’s working as expected!

I forgot to remove the console.log() statements, feel free to remove them!