【问题标题】:Django AJAX form and Select2Django AJAX 表单和 Select2
【发布时间】:2021-08-24 11:42:25
【问题描述】:

我正在使用 AJAX 将表单呈现到我的网站上(查看下方)

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)

使用以下 JQuery 代码在按钮单击时呈现表单和模式:

$(".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);
            }
        });
    });

我遇到的问题是我正在尝试使用 Select2,并且由于在 DOM 加载后正在呈现表单,因此 Select2 无法正常工作。有没有人有办法解决这个问题?观察 DOM 的变化并启用 Select2?

非常感谢

【问题讨论】:

  • 单击按钮时,会打开一个模式然后呈现表单?

标签: django django-templates jquery-select2


【解决方案1】:

也就是select2初始化,你可以把这段代码放在你的jQuery AJAX方法的成功回调中。

请不要忘记将my_select_element 替换为表单中输入元素的idclass name,无论您想在哪里触发select2。

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

为简单起见,我将整个 AJAX 代码放在下面-

$(".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();

        }
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-10
    • 2012-03-14
    • 2014-04-11
    • 2018-08-08
    • 2014-12-07
    • 1970-01-01
    • 2013-09-28
    • 2019-06-27
    相关资源
    最近更新 更多