How do I use a dropdown menu selection to filter a table htmx style?

188 views Asked by At

I have a drop down list which is populated in the same way as the table, and represents the first column. I am trying to figure out how to drop down, select, then have the table refresh htmx style to show just the row corresponding to the selection in the dropdown. The table is created from a fastapi endpoint but once the page is loaded shouldn't I be able to just filter the table? My jinja2 is working fine to load the sections. I feel like I'm miss something extremely basic. But after 2 months of learning python and website dev from nothing, I don't feel so bad.

Help me Stack Overflow. You're my only hope.

Here is the relevant part of the table section in its own file:

    <tbody class="tw-font-medium dark:tw-border-gray-700 text-center" id="gpios">
        {% include 'components/gpio.html' %}
    </tbody>

And here is the gpio.html:

{% for gpio in gpios %}
    <tr>
    <td class="border">
        {{ gpio.gpio }}
    </td>
    <td class="border">
        {{ gpio.name }}
    </td>
    <td class="border">
        {{ gpio.type }}
    </td>
    <td class="border">
        {{ gpio.state }}
    </td>
    <td class="border">
        {{ gpio.changed }}
    </td>
    </tr>
{% endfor %}

This also populates the dropdown:

<form method="get">
        <button class="btn btn-primary dropdown-toggle p-2"
              type="button" id="gpioDropdown"
              data-bs-toggle="dropdown" aria-expanded="false"
              hx-get="/"
                hx-select="value"
              hx-trigger="change"
              hx-target="#test">
        Select GPIO
        </button>
        <ul class="dropdown-menu" aria-labelledby="gpioDropdown">
        {% for gpio in gpios %}
          <li><a class="dropdown-item" value="{{ gpio.gpio }}">{{ gpio.gpio }}</a></li>
        {% endfor %}
        </ul>
</form>
1

There are 1 answers

1
Panke On

You need to trigger a request when an item of the dropdown menu is selected. The response should include the new table (with just one row) and should replace the table in your current page.

To do this, I'd use a <select>, containing <option> for the dropdown. hx-target your table with hx-swap="outerHTML".