【问题标题】:select2 dropdownlist doesnt close after clicking the "add" button单击“添加”按钮后,select2 下拉列表未关闭
【发布时间】:2022-01-04 08:57:59
【问题描述】:

我在 select2 下拉列表中添加了一个“添加新人”按钮

select2 代码如下所示:

  $('#subFundSelection').select2({
            width: '100%',
            placeholder: 'Select a sub-fund',
            ajax: {
                url: '/FundInfo/SearchLegalEntities',
                type: 'GET',
                dataType: 'json',
                delay: 250,
                allowClear: true,
                data: function (params) {
                    return {
                        searchTerm: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: $.map(data.legalEntities, function (obj) {
                            return { id: obj.Id, text: obj.Text };
                        })
                    };
                },
            },
            minimumInputLength: 2
        }).on('select2:open', () => {
            $(".select2-results:not(:has(button))").append('<button id="newPersonButton" style="width: 100%" type="button" class="btn btn-primary" onClick="CreateLegalEntity()">+ Add a new person</button>')
        })

下拉列表中添加了一个按钮(我无法添加图片抱歉)

当我点击这个“添加新人”按钮时,我会打开一个模式。

function CreateLegalEntity() {
  
   $('#CreateLegalEntityModal').modal('show');
}

一切正常,而不是下拉列表在单击后没有关闭并且它出现在模式的顶部,直到我单击屏幕中的其他位置。

很抱歉没有附上截图,但网站不允许我。

我试过了:

$(this).blur() 
$(".select2").trigger('blur') 
$(".select2").trigger('change')

【问题讨论】:

    标签: javascript dropdown jquery-select2


    【解决方案1】:

    来自Methods | Select2这里的 SELECT2 文档

    close 方法会导致下拉菜单关闭,隐藏可选择的选项:

    $('#subFundSelection').select2('close');
    

    应该做你想做的事

    编辑

    您应该从最初创建元素 .select2({params}); 的同一标识符调用 .select2('close') 方法

    例如:$('#div1').select2() 所以应该是$('#div1').select2('close')

    【讨论】:

    • 嗨@slashroot,感谢您的回复。我已将其添加到函数 CreateLegalEntity() { $('.select2').select2('close'); $('#CreateLegalEntityModal').modal('show'); } 但它似乎没有工作。现在看起来连模态都没有打开
    • 编辑:我已经编辑直接指向我的带有 ID 的
    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多