tmuat
tmuat

Reputation: 13

Django AJAX form and Select2

I am rendering a form on to my site with AJAX (view below)

def add_property_and_valuation(request):
    """
    A view to return an ajax response with add property & valuation form
    """

    data = dict()

    form = PropertyForm()

    context = {"form": form}
    data["html_modal"] = render_to_string(
        "properties/stages/add_property_and_valuation_modal.html",
        context,
        request=request,
    )
    return JsonResponse(data)

The form and modal render on button click with the following JQuery code:

$(".js-add-property").click(function () {
        var instance = $(this);
        $.ajax({
            url: instance.attr("data-url"),
            type: 'get',
            dataType: 'json',
            beforeSend: function () {
                $("#base-large-modal").modal("show");
            },
            success: function (data) {
                $("#base-large-modal .modal-dialog").html(data.html_modal);
            }
        });
    });

The issue I am having is that I am trying to use Select2 and because the form is being rendered after the DOM has loaded Select2 isn't working. Does anyone have a way to work around this? Watch for the DOM to change and enable Select2?

Many thanks

Upvotes: 0

Views: 1169

Answers (1)

Gaurav Sharma
Gaurav Sharma

Reputation: 107

That is called select2 initialization, you can put this code in the success callback of your jQuery AJAX method.

Just do not forget to replace my_select_element with the id or class name of your input element in the form, wherever you want to trigger the select2.

// here "my_select_element" is the "id" of your HTML form input element where you want to apply select2.
$('#my_select_element').select2();

For simplicity, I am putting the whole AJAX code below-

$(".js-add-property").click(function () {
    var instance = $(this);
    $.ajax({
        url: instance.attr("data-url"),
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
            $("#base-large-modal").modal("show");
        },
        success: function (data) {
            $("#base-large-modal .modal-dialog").html(data.html_modal);

            // Initialize the select2 on newly rendered form
            // here "my_select_element" is the "id" of your HTML form input element where you want to apply select2.
            $('#my_select_element').select2();

        }
    });
});

Upvotes: 1

Related Questions