javascript Select2 输入框中的 Select2 预加载标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20145134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:51:49  来源:igfitidea点击:

Select2 preloaded tags in Select2 input box

javascriptjqueryautocompletejquery-select2

提问by imperium2335

I have a Select2 input that is working great. The user can start typing and select an option from the dropdown menu and it adds a tag into the input field, they can also create their own tags thanks to the createSearchChoicefunction.

我有一个运行良好的 Select2 输入。用户可以开始输入并从下拉菜单中选择一个选项,并在输入字段中添加一个标签,由于该createSearchChoice功能,他们还可以创建自己的标签。

My scenario is when a user types in a customer's name who already exists, it locks on, and I want it to populate the field with tags (usual suppliers). The user can then delete or add more tags if they want.

我的场景是当用户输入已经存在的客户名称时,它会锁定,并且我希望它用标签(通常是供应商)填充该字段。然后,用户可以根据需要删除或添加更多标签。

My code is:

我的代码是:

$('#usualSuppliers').select2({
        containerCssClass: 'supplierTags',
        placeholder: "Usual suppliers...",
        minimumInputLength: 2,
        multiple: true,
        placeholder: 'Usual suppliers...',
                createSearchChoice: function(term, data) {
            if ($(data).filter(function() {
                return this.name.localeCompare(term) === 0;
            }).length === 0) {
                return {id: 0, name: term};
            }

        },
        id: function(e) {
            return e.id + ":" + e.name;
        },
        ajax: {
            url: ROOT + 'Ajax',
            dataType: 'json',
            type: 'POST',
            data: function(term, page) {

                return {
                    call: 'Record->supplierHelper',
                    q: term
                };
            },
            results: function(data, page) {
                return {
                    results: data.suppliers
                };
            }
        },
        formatResult: formatResult,
        formatSelection: formatSelection,
        initSelection: function(element, callback) {
            var data = [];
            $(element.val().split(",")).each(function(i) {
                var item = this.split(':');
                data.push({
                    id: item[0],
                    title: item[1]
                });
            });
            //$(element).val('');
            callback(data);
        }
    });

How can I make it pre-populate the input with tags that come in from an Ajax request?

如何使用来自 Ajax 请求的标签预填充输入?

回答by imperium2335

I managed to solve the issue thanks to this post:

由于这篇文章,我设法解决了这个问题:

Load values in select2 multiselect

在 select2 多选中加载值

By using trigger.

通过使用触发器。