htmx: hx-trigger for a change event in a child element
Asked Answered
D

2

9

I use htmx together with the Django forms library.

Here is my template:

<table>
 <tr hx-post="{{ object.get_absolute_url }}" hx-swap="outerHTML" 
     hx-trigger="changed">
  <th>{{ object.leg.start }}</th>
  <th>--&gt;</th>
  <th>{{ object.leg.end }}</th>
  <th>{{ object.leg.distance }}m</th>
  <th>{{ object.leg.difficulty_verbose }}</th>
  <td>{{ form.runner }} {{ form.runner.errors }}</td></tr>
</table>

Here is the created html:

<table>
 <tr hx-post="/leg/155/Talfreunde/ %}" hx-swap="outerHTML" hx-trigger="changed">
  <th>Schöneck</th>
  <th>--&gt;</th>
  <th>Mühlleithen</th>
  <th>13400m</th>
  <th>hard</th>
  <td>
    <select name="runner" required id="id_runner">
     <option value="">---------</option>
     ...
    </select>
  </td>
 </tr>
</table>

I want the <tr> to act like a form.

I tried to find a way to tell hx-trigger to listen for the change event of the <select>.

How to tell htmx to submit the data as soon as the select was changed?

Background: This is a Relayrace and each leg will be a row in the table.

Diclinous answered 10/1, 2021 at 16:18 Comment(0)
D
12

You need to use the change event. The term changed does mean something different.

<script src="https://unpkg.com/[email protected]"></script>

<table>
 <tr hx-post="//example.com" hx-trigger="change">
  <td>
    <select name="runner">
     <option value="a">a</option>
     <option value="b">b</option>
    </select>
  </td>
 </tr>
</table>
Diclinous answered 10/1, 2021 at 19:29 Comment(2)
This works as intended for select elements. Is there a way to make this work for input elements too? Using hx-trigger="change" only triggers on blur, not on keyup.Rattly
@Rattly I sugguest you asks a new question here at Stackoverflow. I can't dive into this at this moment.Diclinous
M
1

I had a similar problem with a select within a form. I did not want to post the whole form neither write complex JS.

In each , I add a data-url which contains the url to be used when the select option is changed.

in the hx-on:change property of the select, I do the query via htmx.ajax(), using the data-url of the selected option (this.options[this.selectedIndex].dataset.url).

Hope this can help.

<div class="col-md-3">
    <label for="id_batch_id" class="form-label">Filtre sur les lots</label>
    <select name="batch_id" id="id_batch_id" class="form-select form-select-sm" hx-on:change="htmx.ajax('GET', this.options[this.selectedIndex].dataset.url, '#page')">
        <option data-url="{{ url_for('get_payment_list') }}">- Aucun -</option>
        {% for batch in context.batches %}
        <option data-url="{{ url_for('get_payment_list', batch_id=batch.id) }}" {% if batch.id==context.batch_id | int %}selected{% endif %}>
        {{ batch.name }} • {{ batch.description }}
        </option>
        {% endfor %}
    </select>
</div>
Measureless answered 20/4 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.