Search code examples
javascripthtmlhtmx

Multiple targets for Htmx


I have multiple triggers on my htmx.

<input list="users_list" type="text" name="user_name" class="search-bar" placeholder="Username"
    id="user_search_bar"
    value=""
    hx-trigger="keyup delay:500ms, change"
    x-headers='{"X-CSRFToken": "{{ csrf_token }}"}'
    hx-post="{% url 'search_user' %}"
    hx-target="#users_list"
    <datalist id="users_list">
          <option value="elem">elem</option>
    </datalist>

How can I declare one target for each trigger. For exemple when the trigger is "keyup delay" the target should be "users_list", if the trigger is "change" the target should be "endor_list"


Solution

  • The only way to do this just with HTMX is to take advantage of inheritance and use a couple of nested outer elements around the input.

    Each outer element will have its own trigger and target attributes. You can also have different hx-post attributes on each one or leave it in the input. Here's the example code:

    <div hx-target="#vendor_list" hx-trigger="change" hx-post="/vendor">
    
        <div hx-target="#users_list" hx-trigger="keyup delay:500ms" hx-post="/users">
    
            <input list="users_list" type="text" name="user_name" class="search-bar" placeholder="Username" id="user_search_bar" value="">
    
            <datalist id="users_list">
                <option value="elem">elem</option>
            </datalist>
    
        </div>
    
    </div>
    
    <div id="vendor_list">
        vendor list
    </div>
    

    This works because when the element that "catches" the event will use the target specified within the element itself. You can see it working here https://codepen.io/jreviews/pen/PodpMYd