简体   繁体   English

更改 select2 ajax 标签中的选项数据值

[英]change option data value in select2 ajax tags

I have this code for select2 tags method using ajax:我有使用 ajax 的 select2 标签方法的代码:

json data: json 数据:

[
    {
        "id": "5",
        "text": "laravel3"
    },
    {
        "id": "4",
        "text": "laravel2"
    }
]

Code:代码:

$(document).ready(function(){
    $('#tag_list').select2({
        placeholder: "Choose tags...",
        tags: true,
        minimumInputLength: 3,
        tokenSeparators: [",", " "],
        createSearchChoice: function(term, data) {
            if ($(data).filter(function() {
                return this.text.localeCompare(term) === 0;
            }).length === 0) {
                return {
                    id: term,
                    text: term
                };
            }
        },
        ajax: {
            url: '/tags/find',
            dataType: 'json',
            data: function (params) {
                return {
                    q: $.trim(params.term)
                };
            },
            processResults: function (data) {
                return {
                    results: data
                };
            },
            delay: 250,
            cache: true
        }
    });
});

With my code I can search and select data from database or add new tag to my select2 area.使用我的代码,我可以从数据库中搜索 select 数据或将新标签添加到我的 select2 区域。 Now when I select data from database, <option value=""> is data id but when I add new tag <option value=""> is name (text) like this:现在,当我从数据库中获取 select 数据时, <option value="">是数据id ,但是当我添加新标签时, <option value="">是这样的name (文本):

在此处输入图像描述

Now I need to change option value (get database data) from data id to data name (text).现在我需要将选项value (获取数据库数据)从数据id更改为数据name (文本)。 How do change option data value from id to name?!如何将选项数据值从 id 更改为 name?!

Update: I've added more background and references to the docs, and switched the JSFiddle to using $.map() as the docs do.更新:我添加了更多背景和对文档的引用,并将 JSFiddle 切换为使用$.map()作为文档。

The Select2 data format is described in the docs: Select2 数据格式在文档中进行了描述:

Select2 expects a very specific data format [...] Select2 requires that each object contain an id and a text property. Select2 需要一个非常具体的数据格式 [...] Select2 要求每个 object 包含一个id和一个text属性。 [...] Select2 generates the value attribute from the id property of the data objects... [...] Select2 从数据对象的id属性生成value属性...

The docs also describe how to use something other than your id :文档还描述了如何使用除您的id以外的其他内容:

If you use a property other than id (like pk ) to uniquely identify an option, you need to map your old property to id before passing it to Select2.如果您使用id以外的属性(如pk )来唯一标识选项,则需要在将旧属性 map 传递给 Select2 之前将其转换为id If you cannot do this on your server or you are in a situation where the API cannot be changed, you can do this in JavaScript before passing it to Select2如果您无法在服务器上执行此操作,或者您处于无法更改 API 的情况,您可以在将其传递给 Select2 之前在 JavaScript 中执行此操作

In your case, this would mean transforming the data you get back from your AJAX call, so that the id element of each result is actually the text value.在您的情况下,这意味着转换您从 AJAX 调用返回的data ,以便每个结果的id元素实际上是text值。

You can do that with the processResults() AJAX option .您可以使用processResults() AJAX option来做到这一点。 To do that using $.map as the docs do:要做到这一点,使用$.map作为文档:

processResults: function (data) {
    return {
        // Transform data, use text as id
        results: $.map(data, function (obj) {
            obj.id = obj.text;
            return obj;
        })
    };
}

Here's a working JSFiddle .这是一个有效的 JSFiddle Note I've set it up to simulate your real AJAX request using JSFiddle's /echo/json async option.请注意,我已将其设置为使用 JSFiddle 的/echo/json异步选项模拟您的真实 AJAX 请求。

And here's a screenshot of the generated source, showing the value of both added tags, and those retrieved via AJAX, are the name ( text ):这是生成的源代码的屏幕截图,显示了两个添加标签的value ,以及通过 AJAX 检索到的标签的名称( text ):

生成的 Select2 选项

Try this:尝试这个:

ajax: {
    url: '/tags/find',
    dataType: 'json',
    data: function (params) {
        return {
            q: $.trim(params.term)
        };
    },
    //updated 
    processResults: function (data) {
        var newData = [];
        $.each(data, function (index, item) {
            newData.push({                        
                    id: item.id, //id part present in data                        
                    text: item.text //string to be displayed
            });
        });
        return { results: newData };
    },
    //
    delay: 250,
    cache: true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM