Search code examples
djangojquery-select2htmx

Select2 blocks htmx hx-get


I'm using select2 on my form select with htmx but for some reason hx-get does not send any request while form field has select2

I was trying to turn off select2 and everything works fine, so how can i fix that?

template.html

<form method="get" class="mb-3">
    <div class="well">
        <div class="row">
            <div class="form-group col-sm-4 col-md-4 mb-3">

                <div class="custom-select">
                    {% render_field form.contractor_object|add_class:'form-select' hx-get="/customer/worklog/" hx-target='#id_test' hx-select="#id_test" %}
                </div>
            </div>
            <div class="form-group col-sm-4 col-md-4 mb-3">
                <div class="custom-select" id="id_test">
                    {% render_field form.contractor_section|add_class:'form-select' %}
                </div>
            </div>
        </div>
    </div>
    <div class="mt-4 custom-label">
        <div class="row">
            <div class="col">
                <button type="submit" class="btn btn-outline-primary">Поиск</button>
                <a class="btn btn-outline-primary" href="{% url 'customer_worklog' %}">Сброс</a></div>
        </div>
    </div>
</form>

<script>
    $(document).ready(function () {
        $("#id_contractor_object").select2();
    });
</script>

<script>
    $(document).ready(function () {
        $("#id_contractor_counter").select2();
    });
</script>

<script>
    $(document).ready(function () {
        $('#id_contractor_section').select2();
    });
</script>

Solution

  • Select2 plugin transforms the element you originally defined in your markup, that's why htmx stops working on that element. An easy workaround is to set the hx attributes on the select element's parent, and listen for event from the select element using the from modifier. In this case, it can look something like:

    <div class="custom-select" 
        hx-get="/customer/worklog/" 
        hx-target="#id_test"
        hx-trigger="change from:#id_contractor" //or whatever selector points to the selector field. 
        hx-select="#id_test">
        {% render_field form.contractor_object %}
    </div>
    

    This should work even with select2 instantiated.