djangohtmx

How to Reset form field after submit in HTMX


I'm tried to reset form field after submit the data in HTMX. Please guide me how to do.


Solution

  • You can do with with htmx beforeswap https://htmx.org/docs/#modifying_swapping_behavior_with_events

    To make the example below work django view must return HttpResponse(status=204)

    htmx.on("htmx:beforeSwap", (e) => {
            if (!e.detail.xhr.response) {
                var title = $('#id_title');
                if (title) {
                    title.val('');
                }
            }
        })
    

    Tutorial how to work with django forms and htmx https://blog.benoitblanchon.fr/django-htmx-modal-form/