Select2 "change" event does not trigger htmx

Viewed 865

This works, the way I want it: If the <select> gets changed, then htmx gets triggered.

<script src="https://unpkg.com/htmx.org@1.1.0"></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>

If I use a django-autocomplete-light widget, then it does not work.

I use this version: django-autocomplete-light==3.8.1

2 Answers

Just come across this same issue, and fixed it with the following modified version of guettli's answer.

window.addEventListener("DOMContentLoaded", (e) => {
    $('select').on('select2:select', function (e) {
        $(this).closest('select').get(0).dispatchEvent(new Event('change'));
    });
});

If I add this JS, then it works. Better solutions are welcome.

<script>
 window.addEventListener("DOMContentLoaded", (e) => {
  $('select').on('select2:select', function (e) {
   $(this).closest('tr').get(0).dispatchEvent(new Event('change'));
});
 })
</script>
Related