8

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

guettli
  • 25,042
  • 81
  • 346
  • 663

4 Answers4

10

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'));
    });
});
Dane Lewis
  • 119
  • 1
  • 7
4

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>
guettli
  • 25,042
  • 81
  • 346
  • 663
2

For me it worked when also adding htmx.onLoad() using bootstrap 5 styled Select2 https://apalfrey.github.io/select2-bootstrap-5-theme/:

htmx.onLoad(() => {
   $("#collection-select").select2({
      theme: "bootstrap-5",
      closeOnSelect: true
   });
});
window.addEventListener("DOMContentLoaded", (e) => {
   $('select').on('select2:select', function (e) {
      $(this).closest('select').get(0).dispatchEvent(new Event('change'));
   });
});
et97
  • 75
  • 1
  • 6
1

What worked for me was to trigger the change event with the htmx javascript API trigger https://htmx.org/api/#trigger

window.addEventListener("DOMContentLoaded", (e) => {
  $('select').on('select2:select', function (e) {
    htmx.trigger($(this).closest('select').get(0), 'change')
  })
})
daniboygg
  • 15
  • 6