简体   繁体   中英

Select2 "change" event does not trigger htmx

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

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>

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'));
    });
});

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'));
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM