Search code examples
htmljquerydjango-formshtmx

How can I using jQuery dynamically add HTML elements containing htmx-attributes?


I'm encountering an issue with Django forms within a formset being dynamically inserted using jQuery and containing HTMX attributes (hx-get, hx-trigger, hx-target). Initially, when the forms are loaded, the HTMX attributes work perfectly. However, the problem arises when I dynamically insert additional forms via jQuery – the newly injected forms lack any attached event listeners, rendering the HTMX attributes ineffective.

I'm looking for a way to ensure that the dynamically inserted forms retain these event listeners and correctly trigger the HTMX functionality.

<div class="tab-content" id="courseTabContent">
    <div class="tab-pane fade active show" id="nav_id_item-0-id">
        <div id="image-placeholder_item-0" hx-get="/path/to/view" hx-trigger="click" hx-target="#modal-placeholder-xl">
            <!-- initially loaded // htmx working -->
        </div>
    </div>
    <div class="tab-pane fade" role="tabpanel" tabindex="0" id="nav_id_item-1-id">
        <div id="image-placeholder_item-1" hx-get="/path/to/view/" hx-trigger="click" hx-target="#modal-placeholder-xl">
            <!-- injected by AJAX request // htmx not working-->
        </div>
    </div>
</div>

I've tried various approaches, including reapplying HTMX attributes or reinitializing the listeners after inserting the form, but so far, none have yielded the desired result.

How can I ensure that the HTMX attributes function correctly on dynamically inserted forms within the Django formset?

Thank you in advance for any insights or guidance!


Solution

  • If elements are inserted with htmx attributes, they have to be initialized using htmx.process():

        <div id="some_new_content" hx-get="/path/to/view/" hx-trigger="click" hx-target="#modal-placeholder-xl">
        </div>
    
        <script>
           var elt = $('#some_new_content')[0];
           htmx.process(elt);
        </script>
    

    https://htmx.org/api/#process