I have two select fields in my form. The first is a select2, the second is a regular HTML one.
I want to replace the second one with HTMX when I select something in the first. In addition, I need to know what was selected in the first one.
And, because I'm using HTMX I want to avoid loads of ugly JS/jQuery 👻
I know that I can listen to the event select2.select but my HTMX never triggers.
<select id="second-select" hx-get="/my-url" hx-trigger="select2.select from:body">...</select>
I also tried hx-trigger="select2.select from:#select1"
.
Any ideas what I might be doing wrong and how I can pass the selected value from the first select?
Thx!
Ronny
Select2 is a jQuery library, therefore it uses the jQuery event system, not the vanilla JS events, so HTMX cannot catch them by itself. You need to create an event bridge between Select2 and HTMX. In the following example we translate the select2.select
jQuery event to a vanilla JS event and dispatch it to the second select element triggering the HTMX request.
<select id="second-select" hx-get="/my-url" hx-trigger="select2.select">...</select>
<script>
$(document).ready(function () {
// Init Select2 on #first-select element
$('#first-select').select2();
// Attach to 'select2:select' jQuery event from Select2
$('#first-select').on('select2:select', (e) => {
// Dispatch 'select2:select' vanilla JS event to trigger HTMX
let event = new Event('select2:select');
document.querySelector('#second-select').dispatchEvent(event);
});
});
</script>