Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}, {
    "id": "8",
    "text": "CTest"
}, {
    "id": "13",
    "text": "DTest"
}];


$("#mylist").select2({
    data: dataUser,
    templateResult: function(data) {
        return data.text;
    },
    sorter: function(data) {    
        return data.sort();
    }
});

http://jsfiddle.net/oe9retsL/4/

This list sorts by id, but I want sort by text.

like image 574
radek. Avatar asked Jan 07 '23 20:01

radek.


1 Answers

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

like image 199
Rory McCrossan Avatar answered Jan 15 '23 09:01

Rory McCrossan