Search code examples
alpine.jshtmx

HTMX and AlpineJS conflicting on listening for a select change event


I'm trying to make HTMX and AlpineJS work together on a select element, what I expect:

  • When user change select value it calls /v2/Url?param=value&selectId=1

What happens:

  • It calls the url without appending selectId query parameter: /v2/Url?param=value

Best code that I can think of:

<select 
    name="selectId" 
    id="selectId"

    hx-get="/v2/Url?param=value"
    hx-target="#targetId" 

    x-data="{ disabled: false }"
    x-bind:disabled="disabled" 
    x-on:change="disabled = true" 
    x-on:htmx:after-on-load="disabled = false">

    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
</select>


<div id="targetId">

</div>

When I remove the x-on:change="disabled = true" HTMx works fine, but when I add it, looks like HTMx stop listening for the change event.


Solution

  • Following @Alejandro comment I was able to solve this issue using alpine $nextTick function, final code:

    <select 
        name="selectId" 
        id="selectId"
    
        hx-get="/v2/Url?param=value"
        hx-target="#targetId" 
    
        x-data="{ disabled: false }"
        x-bind:disabled="disabled" 
        x-on:change="$nextTick(() => disabled = true)"
        x-on:htmx:after-on-load="disabled = false">
    
        <option value="1">Item 1</option>
        <option value="2">Item 2</option>
        <option value="3">Item 3</option>
    </select>
    
    
    <div id="targetId">
    
    </div>