In Select2, how do formatSelection and formatResult work?
You need to add the function like explained here. In your example:
function format(state) {
return state.text;
}
GBC
Building web apps for a project about content curation. It's just the beginning...
Updated on May 15, 2020Comments
-
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 hasid
andtext
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
andformatInput
, 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 about 10 yearsThank 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 about 10 yearsWhat do you mean by nothing? undefined? I not called at all?
-
Vinz243 about 10 yearsCan you log the data after the Ajax?
-
GBC about 10 yearsI 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 about 9 yearsIn 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