htmx
htmx copied to clipboard
Is there a way to avoid multiple hx-swap="afterend"?
I have a layout like
<div class="heading">
</div>
<a hx-target=".heading" hx-swap="afterend" hx-get="/url/to/get/a/form">add a post</a>
so that pressing a add a post link will insert a form under .heading. When the user saves the form, a record will be inserted, replacing the form.
This works fine but users can press the link multiple times and create multiple forms with identical IDs and actions. Is there any way to disallow the insertion of a new form when a form with a certain ID already exists?
Hey, I see you're using afterend so I suppose the form is to be inserted in between the heading and the link.
The following could work:
<div class="heading"></div>
<div id="formAnchor"></div>
<a hx-target="#formAnchor" hx-swap="outerHTML" hx-get="/url/to/get/a/form">add a post</a>
I've added an empty element here to be targeted to insert the form. This solves the issue where multiple clicks bring multiple forms in, because it always replaces the formAnchor so there can only be 1 at a time.
Example form response:
<form id="formAnchor" hx-post="/record" hx-target="this" hx-swap="outerHTML">
...
</form>
The ID is carried around here so that whether it's the empty element or the actual form, a #formAnchor element always exist. So clicking on the link multiple times will replace the form if it already exists.
Then you can use OOB swapping to insert your record while removing the form on submit, such as:
<div hx-swap-oob="beforebegin:#formAnchor">
<div class="record">A record</div>
</div>
<div id="formAnchor"></div>
Responding this to the /record POST request will replace your form by the empty element (thus making it disappear for your user), while inserting the new record right before the formAnchor.
You can try it on this JSFiddle, however please note there seems to be an issue with the demo script that triggers requests twice so don't pay attention to that
Let me know if this suits your usecase!