George Livanoss
George Livanoss

Reputation: 599

htmx, push url with form value

I've decided to try htmx. I have a form with a input named search, how can I push the input value in the url with hx-push-url

hx-push-url="/?q=

Is not clear to me how to do it with plain htmx. Do I need hyperscript?

Upvotes: 2

Views: 1488

Answers (2)

Van Hudson Galvoso
Van Hudson Galvoso

Reputation: 86

hx-get and hx-push-url="true" must be sufficient, just replace the input name from "search" to "q".

<form hx-get="/yourresource" hx-push-url="true" hx-params="q">
  <input type="text" name="q" />
  <input type="submit" value="Go" />
</form>

if you have other inputs, you can use hx-params="q" but other inputs will be not passed on the request

<form hx-get="/yourresource" hx-push-url="true" hx-params="q">
  <input type="text" name="q" />
  <input type="text" name="otherInput" />
  <input type="submit" value="Go" />
</form>

the "otherInput" will not be handled

Ref: https://htmx.org/attributes/hx-params/

Upvotes: 1

mariodev
mariodev

Reputation: 15484

When generating response (from the search request), you need to add the url into response header called HX-Push-Url, before returning the response in your view (example for django).

response['HX-Push-Url'] = "/?q=foobar"
return response

Htmx will procees it on response and push whatever url you've added.

Ref: https://htmx.org/reference/#response_headers

Upvotes: 1

Related Questions