I’m using htmx in a HTML form in a page basically looking like this:
<form id="my_form" method="post" hx-post="{{ MY_TARGET_URL }}" hx-trigger="click from:.btn delay:100ms">
<input type="hidden" name="state" value="" id="id_state">
<!-- my form contains other inputs as well -->
</form>
<button type="button" class="btn" id="btn1" data-state="1">Submit 1</button>
<button type="button" class="btn" id="btn2" data-state="2">Submit 2</button>
The HTML page also includes the following JavaScript code:
document.querySelectorAll(".btn").forEach((element) => {
element.addEventListener("click", () =>
document.getElementById("id_state").value = element.dataset.state;
);
});
Everything seems to work perfectly well like this: the user can submit the form either by clicking on Submit 1
or on Submit 2
, the hidden input gets updated either with the value 1
or 2
and then 100 ms later the form is submitted, sending a POST request to the specified endpoint.
However, I can feel this solution is a bit hacky and inelegant. Do you see a cleaner way to achieve the same thing, without “delay”?