How can I filter multiple field using checkbox and HTMX?

731 views Asked by At

I have been learning HTMX to combine with MODX CMS, Tailwind and AlpineJS (my weapons of choice) and have gotten a nice HTMX based product filter now.

Dev front-end of product page with HTMX, MODX CMS and Tailwind.

The filter works on click now with:

<input hx-get="product-list.html?color=blue" hx-trigger="click" hx-target="#pdopage" hx-swap="outerHTML" id="blue" name="blue[]" value="blue" type="checkbox">

the hx-get field url product-list.html?color=blue is auto generated by the MODX CMS when site manager add or remove tags.

On the product-list.html page I load all products in HTML using the CMS. Any filters added like: ?group1=tag1&group2=tag2 are already working on the front-end and I plan to get these using HTMX with AJAX.

What I still can't get to work:

  • I need to somehow 'save' any filters that have been selected, so that you can filter by multiple tags.(when someone clicks on color: blue the products filter, this works now, but when they click on Color: Green next the product only display the filter green and we have 'lost' the blue color)
  • Also I need to be able to 'undo' a filter when you click the checkbox filter a second time.

Can anybody show me how to allow for filtering by multiple tags? Maybe somehow save the filter state with JS? Or is there a native HTMX option I don't know about?

Use JS to save clicked filters on click and add it to the genearted URL, but this does not work.

1

There are 1 answers

0
McPherson On

To filter your products based on multiple user-selected tags, you can send an htmx request with every change event on your checkbox elements and include all their values by using hx-include.

To avoid duplication of code, you can wrap your checkboxes in a container and place the htmx attributes there (since most events bubble up to the HTML body).

<div hx-get="product-list.html"
     hx-trigger="change from:body #blue,#green,#red"
     hx-swap="outerHTML"
     hx-target="#pdopage"
     hx-include="#blue,#green,#red">
    <input type="checkbox" id="blue" value="blue" name="blue[]">
    <input type="checkbox" id="green" value="green" name="green[]">
    <input type="checkbox" id="red" value="red" name="red[]">
</div>

Then in your backend, you can retrieve the selected values and do your filtering.