Triggers, forms, and feedback
Enhance a real form
Keep labels, action, method, validation, submit behavior, and server response useful before adding asynchronous replacement.
8 minute lesson
Start with a complete form:
<form id="new-task" action="/tasks" method="post"
hx-post="/tasks"
hx-target="#task-list"
hx-swap="outerHTML">
<label>Task <input name="title" required></label>
<button type="submit">Add</button>
</form>
The action and method define the normal browser submission. The server should return a complete page with either the updated list or a form containing validation errors when JavaScript is unavailable.
For an HTMX request, success can return a complete replacement for #task-list. Validation needs a different target, so the server can respond with safe form HTML plus:
HTTP/1.1 422 Unprocessable Content
HX-Retarget: #new-task
HX-Reswap: outerHTML
Configure htmx:beforeSwap once to allow the intentional 422 fragment. Preserve safe submitted values and associate each message with its control.
The browser’s required check improves feedback but is not server validation. Submit the endpoint directly with an empty title and confirm the same rule still runs.
Finally, disable JavaScript. Creating a valid task and correcting an invalid one should still be possible through full-page responses.
Lesson completed