iamryandrake iamryandrake - 2 months ago 12
Javascript Question

Select2 jQuery Plugin: Is there a way to sort a list of tags alphabetically?

I'm using Select2 plugin (http://ivaynberg.github.io/select2/) and as you can see by the list of tags I have in the screenshot, they aren't listed alphabetically and I'd like to be able to do so.

enter image description here

EDIT: This is what I currently have, but instead of query, I want to sort the data (@appTags) via 'text', not 'id':

scope.find('input[name=noun]').select2({
data: @appTags,
sortResults: function(results, container, query) {
if (query.term) {
return results.sort();
}
return results;
}
});


Screenshots of my Console paused in Debugger:

enter image description here

Here's an image of the @appTags object, of which I'd like to sort via 'text':

enter image description here

Answer

Here is a bit of code from the docs that is using the JS built in sort function. I modified it to sort alphabetically instead of by length as they did in the docs.

$('#e22').select2({
    sortResults: function(results, container, query) {
        if (query.term) {
            // use the built in javascript sort function
            return results.sort();
        }
        return results;
    }
});
Comments