2
votes

I have this code for select2 tags method using ajax:

json data:

[
    {
        "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. 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:

enter image description here

Now I need to change option value (get database data) from data id to data name (text). How do change option data value from id to name?!

2
How are you adding the newtag option to your select2 dropdown?Terry
@Terry newtag is type a newtag and enter...LarakBell
@LaraBell at what use you are using select box?.. it might be submitting data to server right?...that time you need id's instead of text...so preserving id's as values is better.Mohammedshafeek C S

2 Answers

3
votes

Update: I've added more background and references to the docs, and switched the JSFiddle to using $.map() as the docs do.

The Select2 data format is described in the docs:

Select2 expects a very specific data format [...] Select2 requires that each object contain an id and a text property. [...] Select2 generates the value attribute from the id property of the data objects ...

The docs also describe how to use something other than your 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. 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

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.

You can do that with the processResults() AJAX option. To do that using $.map as the docs do:

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. Note I've set it up to simulate your real AJAX request using JSFiddle's /echo/json async option.

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):

Generated Select2 options

1
votes

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
}