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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With