skip to Main Content

I have a button that I want to send two requests to the server when clicking. The setup is like this:

<button id="add-item" hx-get="some-url" hx-trigger="click" hx-target="#item-form" hx-swap="beforeend" type="button">Add item</button>

<br>
<div hx-get="some-other-url" hx-trigger="from: #add-item" hx-swap="beforeend">
        
</div>

I have tried using hx-trigger="click from: #add-item but that does not work either.

The first request sent by add-item is fetched from the server correctly, but the second one from the div is never sent at all. When changing the trigger for the div to something like hx-trigger="click", it works (also needing some content inside it to click).

Is there soemthing wrong with the syntax or why would this not work?

I have imported HTMX like so: <script src="https://unpkg.com/[email protected]" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script>

Any help would be appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    This fixed the problem:

    hx-trigger="from: #add-item" 
    

    replaced with

    hx-trigger="click from:#add-item" 
    

    Specifying the event by writing click was necessary as well as removing the space between from: and #add-item.


  2. The issue you’re facing might be related to the way you’re using the hx-trigger attribute. HTMX’s hx-trigger attribute determines what action triggers the request to the server. When you use hx-trigger="click from: #add-item", it’s trying to listen for a click event from an element with the ID add-item. However, it seems that the button with the ID add-item is the one triggering the request, not the div.

    To send two requests upon clicking the button with ID add-item, you can set up your HTMX attributes as follows:

    <button id="add-item" hx-get="some-url" hx-trigger="click" hx-target="#item-form" hx-swap="beforeend" hx-trigger-boost="true" type="button">Add item</button>
    
    <br>
    <div hx-get="some-other-url" hx-trigger="click: #add-item" hx-swap="beforeend" hx-trigger-boost="true">
    </div>
    

    Here’s what’s changed:

    1. Added hx-trigger-boost="true" to both elements. This ensures that
      the triggering event propagates to the parent element (the div) when
      the button is clicked.
    2. Changed hx-trigger on the div to hx-trigger="click: #add-item". This
      means the div will listen for a click event from the element with
      the ID add-item.
    3. With these changes, when you click the "Add item" button, it will
      trigger both requests as intended.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search