If autofocus and hx-preserve, then input jump each time. Possible workaround?
I have certain data inputs that under rare circumstances are rewritten. I have htmx for invoice validations, that recalculate the invoice line (these values not change in the calculation, but somethings it gets an old value or is rewrited mid-flight in a low-speed connection):
<input id=qty autofocus hx-preserve/>
<input id=discount hx-preserve/>
So, I tough to add hx-preserve to avoid that.
However, this conflicts with the autofocus that has the first input. Because that it has hx-preserve, it causes to move the focus back to it in each validation. Put the focus in that input is important to the fast flow for the screen.
Exist a workaround to it?
P.D: If remove the autofocus the interface loses the focus in each refresh, so looks like this attribute is not meant for inputs?
I'm running into this same issue. Seems like the fundamental problem is that when you're validating an input, you sort of want to preserve parts of it and not others. For instance, if I'm validating a text input, I'd like to preserve the state of the control (e.g. focus or lack of it, cursor position, etc.). I'd like autofocus to only apply when I first load the entire page, not every time I do a validation. But, I'd like to be able to update the class and such to be able to style the control differently (e.g., turn it red by adding an "error" class type to it). It feels like we either need hx-preserve to specific exactly what should be preserved or be "smart" such that it sort of merges state when updating. Today, the choices seem to be complete replacement or hx-preserve which prevent all updates. But maybe I'm missing something. I'm sure I could work around this with js, but that's sort of what htmx is supposed to avoid.
My current work around is this:
- Don't use
hx-preserve. - Do use
autofocusfor the first input when the initial page is downloaded. This causes focus to the correct element. - Recreate and return the input HTML each validation, but with the following changes.
- Don't include
autofocuson the returned HTML. - Do include the validation text as the input
value.
I think there might still be a problem with this since on a slow connection, the user could type something, wait a short bit to trigger validation, then type something while the validation was occurring, after which the replacement HTML comes back from the server which then overwrites the value of the text that the user just typed after validation started. I'll have to think this through. On my local machine, everything is so fast that it just works, but that doesn't mean there isn't a race.
I solve it as described here, but that require to hack the source code.
@mamcx, thanks!