In Select2, how do formatSelection and formatResult work?

20,728

You need to add the function like explained here. In your example:

function format(state) {

    return state.text;
}
Share:
20,728
GBC
Author by

GBC

Building web apps for a project about content curation. It's just the beginning...

Updated on May 15, 2020

Comments

  • GBC
    GBC about 4 years

    I'm using Select2 (http://ivaynberg.github.io/select2/) to have an input field of a form (let's say its id is topics) to be in tagging mode, with the list of existing tags (allowing the user to choose some of these tags, or to create new ones) being provided by an array of remote data.

    The array (list.json) is correctly got from my server. It has id and text fields, since Select2 seems to need these fields. It thus looks like this:

    [ { id: 'tag1', text: 'tag1' }, { id: 'tag2', text: 'tag2' }, { id: 'tag3', text: 'tag3' } ]
    

    The script in the HTML file looks like this:

    $("#topics").select2({
        ajax: { 
            url: "/mypath/list.json",
            dataType: 'json',
            results: function (data, page) { 
            return {results: data};
            },   
        }
    });
    

    But the input field is showing "searching", which means it's not able to use the array for tagging support.

    In the script with Select2, I know I have to define formatSelection and formatInput, but I'm not getting how they should work in my case, although I have read the Select2 documentation... Thank you for your help!

  • GBC
    GBC about 10 years
    Thank you. I tried this: function format(item) { return item.text; } $("#topics").select2({ ajax: { url: "/mypath/list.json", dataType: 'json', results: function (data, page) { return {results: data}; } }, formatResult: format, formatSelection: format, escapeMarkup: function (m) { return m; } }); but it's still not working.
  • Vinz243
    Vinz243 about 10 years
    What do you mean by nothing? undefined? I not called at all?
  • Vinz243
    Vinz243 about 10 years
    Can you log the data after the Ajax?
  • GBC
    GBC about 10 years
    I could log data on the server-side, but could log nothing on the client-side .But I found the problem (message in the console on the client-side): my server was not allowing Cross-Origin Resource Sharing (CORS), and since I was doing tests from a separate HTML file, it could not work. I fixed that. It is now working. Thank you very much for your help and your patience!
  • Michal Przybylowicz
    Michal Przybylowicz about 9 years
    In Select2 4.* the "formatters" have been renamed to templateSelection and templateResult and their signatures have changed as well. Please refer to select2.github.io/announcements-4.0.html