htmx icon indicating copy to clipboard operation
htmx copied to clipboard

hx-select value is accessed/used at swap time, not at post time. (bug? needed documentation? feature request?)

Open e-Dan-K opened this issue 3 years ago • 0 comments
trafficstars

High Level: When making an htmx call with an hx-select value, if you change the hx-select after you have posted your form, it breaks the flow because the swap attempts to use the new value, rather than the value that it was when you posted.

Details: In my site, I have a page with a list of events on it, and a modal dialog that can be used to change any of the events based on the selected event. When these were selected, I was updating my form with the code:

      modalForm.setAttribute('hx-target', htmx_id); 
      modalForm.setAttribute('hx-select', htmx_id);

where htmx_id was a value like "#response_10" or "#response_11", etc. I was running into a problem if you opened a second dialog before the first post was complete, and tracked it down to the hx-select being updated before it was used. If the hx-select is modified before the htmx:beforeSwap, then it appears that htmx gets confused at tries to grab the wrong data from the response.

So in my example, I would put in a post that would update <div id="response_10"> with a new <div id="response_10">, but by the time it was doing the swap, it was trying to extract <div id="response_**11**"> from the html, which was empty. I needed some way to keep htmx focused on the div I had specified at post time.

Proposal(s):

  1. Save all values into the htmx request. (Probably very involved and unlikely to happen any time soon)
  2. Add an hx-select option like target or something similar. So you could have <button hx-get="/info" hx-target="#response_10" hx-select="target">, and it would know to use the same selector that hx-target used when it processes the hx-select. Since the hx-target is saved in the HTTP headers, it would not matter if you changed the form value after submitting (as long as you left hx-select as "target"). (I think this would be fairly easily, and is consistent with the sort of arguments that already exist for hx-target)
  3. If neither change is made, add a reference in the documentation noting at what point in the flow the hx-select is used, so people don't run into this issue in the future...

If any portion of this is unclear, please let me know and I can try to clarify further!

e-Dan-K avatar Jul 28 '22 05:07 e-Dan-K