Search code examples
htmx

How do you toggle query params with multiple checkboxes in HTMX?


I want to make checkboxes that toggle different query parameters.

e.g.

  • 1st checkbox toggles ulid=000
  • 2nd checkbox toggles txid=111
<input
    type="checkbox"
    hx-trigger="change"
    hx-replace-url="true"
    hx-get="?accepted=true" />

the above code adds accepted=true params to the url but doesn't remove when checked again.


Solution

  • You can define name and value and htmx will attach them as query param when making GET request.

    Try this:

    <input
      type="checkbox"
      value="true"
      name="accepted"
      hx-replace-url="true"
      hx-get="/"
      hx-trigger="change"
    />
    

    In case you have multiple checkboxes, you should wrap them with form tag:

    <form hx-get="/" hx-trigger="change" hx-replace-url="true">
        <input
          type="checkbox"
          name="accepted"
          value="true"
        />
        <input
          type="checkbox"
          name="excluded"
          value="true"
        />
    </form>