Search code examples
htmx

Limit what triggers an htmx request


Expected behavior is when focused on the name input in the form, hitting enter should submit the form. What actually happens is that it triggers the X button to remove the website input. Clicking enter again calls the add website button to bring it back, and continues to toggle it when clicking enter.

<form action="/api/test" method="post">
    <label for="name">Name:</label>
    <input
        type="text"
        id="name" 
        name="name"
    />
    
    <label>Websites:</label>
    <div id="websites">
        <div id="website-{{.WebsiteId}}" class="flex my-2">
            <input 
                type="text" 
                name="website-{{.WebsiteId}}" 
            />
            <button hx-swap="delete" hx-trigger="click" 
                    hx-target="#website-{{.WebsiteId}}" 
                    hx-get="/input/website">X</button>
        </div>
    </div>
    <button hx-get="/input/website" hx-trigger="click" hx-target="#websites" 
            hx-swap="beforeend">Add Website</button>
    <div class="flex sm:flex-row flex-col">
        <button type="submit">Add</button>
    </div>
</form>

Video of what is happening on enter click:

Video of what is happening on enter click

I've tried adding the hx-trigger="click" to all the elements that have an htmx request on it. I was hoping that this would limit the requests to just a mouse click, but the problem persists.


Solution

  • You have to add type="button" to first two buttons.

    What happens is when you don't define button type, the form assumes it's of submit type by default, hence your issue.