I have a datatable and add item form which shows as a modal ( bootstrap ) I’m using htmx to add an entry and swap the datatable with latest data.
Now, I want to handle things like validation and errors.
How to approach this problem, I want to close modal and show updated table if request was successful, or I want to keep the modal and show form with error messages on modal.
Can i conditionally swap the target ? if xhr.status == 400, swap id_add_form else if xhr.status == 201 modal.close(); swap id_item_list
here is the outline of my code
<!--begin::Card-->
<div class="card" id="user_list_table">
...
<button
type="button"
class="btn btn-primary"
data-bs-toggle="modal"
data-bs-target="#modal_add_item"
hx-get="/add-item"
hx-target="#add_user_form"
hx-swap="innerHTML"
hx-trigger="click">
Add Item
</button>
<div class="modal">
<form
id="add_item_form"
class="form"
hx-post="/add-item"
hx-trigger="submit"
hx-swap="none"
>
...
</form>
</div>
...
<div id="item_list">
...
</div>
...
</div>
and js
document.addEventListener("htmx:afterRequest", function (event) {
if (event.detail.elt == "add_item_form") {
var form = document.getElementById('add_item_form');
// if event is 200 ok
if (event.detail.xhr.status == 200) {
// close modal
form.reset();
modal.hide();
}
}
}
2
Answers
There is an extention for htmx https://htmx.org/extensions/response-targets/
which allows us to target different elements for different responses.
when combining this with javascript, I could make it work
You can listen to a
beforeSwap
event on the form. The event.detail will have theshouldSwap
attribute which which can conditionally set.