With the help of @Rory McCrossan managed to create such a script to sort the values in the select field. However, there is still a problem - support for Polish characters. Is there any possibility to also be taken into account?
Code:
var dataUser = [{
"id": "5",
"text": "BTest"
}, {
"id": "2",
"text": "ATest"
}, {
"id": "8",
"text": "aTest"
}, {
"id": "13",
"text": "ŁTest"
}];
var dataUser2 = [{
"id": "5",
"text": "DBTest"
}, {
"id": "2",
"text": "FATest"
}];
$("#mylist").select2({
data: dataUser,
templateResult: function(data) {
return data.text;
},
sorter: function(data) {
return data.sort(function(a, b) {
return a.text.toLowerCase() < b.text.toLowerCase() ? -1 : a.text.toLowerCase() > b.text.toLowerCase() ? 1 : 0;
});
}
}).on("select2:select", function(e) {
var $container = $(this).next().find('.select2-selection__rendered');
$container.find('li.select2-selection__choice').sort(function(a, b) {
return $(a).text() < $(b).text() ? -1 : $(a).text() > $(b).text() ? 1 : 0;
}).prependTo($container);
});
$("#mylist2").select2({
data: dataUser2,
templateResult: function(data) {
return data.text;
},
sorter: function(data) {
return data.sort(function(a, b) {
return a.text.toLowerCase() < b.text.toLowerCase() ? -1 : a.text.toLowerCase() > b.text.toLowerCase() ? 1 : 0;
});
}
});
JSFIDDLE
Try to use String.localeCompare instead of < see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
sort(function(a, b) {
return $(a).text().localeCompare($(b).text());
});
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