Skip to content Skip to sidebar Skip to footer

Sort By Name In Select2

Is there any way to sort my list generated by select2 by name? I have some code : var dataUser = [{ 'id': '5', 'text': 'BTest' }, { 'id': '2', 'text': 'ATest' }, {

Solution 1:

You need to provide a function to sort() which contains the logic to compare the text property of each object in the array. Try this:

sorter: function(data) {
    return data.sort(function(a, b) {
        return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
    });
}

Updated fiddle

To sort the selected options you need to implement similar logic on the tag well when an option is selected, like this:

$("#mylist").select2({
    data: dataUser,
    templateResult: function(data) {
        return data.text;
    },
    sorter: function(data) {
        return data.sort(function(a, b) {
            return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
        });
    }
}).on("select2:select", function (e) { 
    $('.select2-selection__rendered li.select2-selection__choice').sort(function(a, b) {
        return $(a).text() < $(b).text() ? -1 : $(a).text() > $(b).text() ? 1 : 0;
    }).prependTo('.select2-selection__rendered');
});

Updated fiddle

Post a Comment for "Sort By Name In Select2"