【问题标题】:Set data in Select2 after insert with AJAX使用 AJAX 插入后在 Select2 中设置数据
【发布时间】:2012-12-28 00:17:39
【问题描述】:

我正在使用带有 AJAX 的 Select2(下面的代码):

$(".select2-ajax").select2({
        placeholder: "Search user",
        minimumInputLength: 1,
        ajax: {
            url: $('#url-search-client').val(),
            dataType: 'json',
            type: 'post',
            data: function (term, page) {
            return {
                filter: term
            };
            },
            results: function (data, page) {
            return {results: data};
            }
        },
        width : '50%',
        formatInputTooShort: function () {return 'Informe mais caracteres'; },
        formatResult: formatResultSelectAjax, // omitted for brevity, see the source of this page
        formatSelection: formatSelectAjaxValue, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
    });

好吧,如果没有找到客户端,用户可以使用一个按钮打开一个模态并添加新客户端,可以使用新客户端的返回(带有 id 和 namee 的 json)并放入数据(如名称)进入select2作为选择?

$('.btn-form-client').click(function() {
        $.ajax({
            url: $('#frm-client').attr('action'),
            dataType: 'json',
            type: 'post',
            data: $('#frm-client').serialize()
        }).done(function (data) {
            $('#modal-client').modal('hide')
        });
        return false;
    });

【问题讨论】:

  • 你能做到吗?

标签: jquery ajax jquery-select2


【解决方案1】:

从 v4.x 开始,select2 不再使用隐藏的 input 字段。相反,你 create a new Option 并将其附加到你的 select 元素:

var newOption = new Option(data.name, data.id, true, true);
$(".select2-ajax").append(newOption).trigger('change');

true 参数和trigger('change') 的组合将确保您的新<option> 在添加后被自动选中。

查看我的codepen 以获得完整的工作示例。

【讨论】:

  • 如果要添加带空格的选项,jquery查找需要固定为用单引号将选项值括起来:if ($("#state").find("option[value='" + newStateVal + "']").length) {
  • @alexw,多选项目怎么样?检查这个jsfiddle:jsfiddle.net/xqhp0z0x/27
  • @chiragsatapara 您可以将一组值传递给.val,但是您需要在初始化 Select2 之后完成所有这些操作。如果您在 github.com/select2/docs 上打开问题,我可以记录下来。
【解决方案2】:

我设法让它工作。在 jQuery 中发布后,我得到一个带有新数据的 JSON 并设置隐藏输入和选择('.select2-ajax')

$('#client=id').val(data.id);
$('#modal-solicitante').modal('hide'); //This is my
$(".select2-ajax").select2('data', {id: data.id, name: data.name, email: data.email});

【讨论】:

    猜你喜欢
    • 2017-01-23
    • 2019-02-22
    • 2022-06-23
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多