I have the following htmx component,
<form hx-trigger="submit" hx-swap="outerHTML" hx-post="/add" hx-target="#list">
<input type="text" name="todo"/>
<button type="submit">Add</button>
</form>
I want to clear the input field once the post request return a 201 response.
I was able to do it using following JS code,
<script>
htmx.on("htmx:afterRequest", (event) => {
// By assuming the `el` is always the input element and the response is always 201 for testing.
const el = event.detail.requestConfig.elt[0]
el.value = '';
})
</script>
Is there any other (better) way to do this ? Perhaps without writing any JS ?
There're few ways to handle it:
_="on htmx:afterSend set my value to ''"
to the input element (pseudo-code)My preference would be to use pt 1) and re-render the html content, just like you would do it without any htmx/js, but it all depends on your specific use case. Maybe inline scripting is good enough for this simple case.