Search code examples
djangoalpine.jshtmx

How to change hx-get value dynamically?


I have a button which opens a dialog located in some_template.html:

<button @click="open = !open"
        id="btn_id"
        hx-get="/some_url/"
        hx-trigger="click"
        hx-swap="outerHTML">
</button>

Then I have another_template.html which includes some_template.html

In another_template.html I am handling a button click:

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('dialog', () => ({
            handleButtonClick(id) {
                console.log(id); // prints the expected id correctly
                const button = document.getElementById('btn_id');
                const url = `/some_url/${id}`;
                button.setAttribute('hx-get', url);
                console.log(button.attributes); // prints the updated `hx-get` with the id included
                button.click();
            }
        }));
    });
</script>

The dialog is opening correctly which means the button.click() is working properly.

The main problem is that the hx-get in the button is not being updated, i.e., there is no id associated with it, and it still processes the request without it, using what was initially defined in the button: hx-get="/some_url/".


Solution

  • The problem is that I was not using htmx.process() after changing the button's attributes. htmx.process() forces htmx to reparse the updated DOM.