Search code examples
htmx

Proper way to clear the input field after form submission with HTMX


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 ?


Solution

  • There're few ways to handle it:

    1. Using hx-swap-oob, as mentioned by @pthomson, to either replace the whole form or the input only.
    2. Using hx-on::after-request attached to input element. This is pretty much an inline version of your solution.
    3. Using hyperscript (htmx sister-lib): attach _="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.