Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polish letters in sorting select2

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

like image 470
radek. Avatar asked Mar 31 '26 16:03

radek.


1 Answers

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());
});
like image 55
Gavriel Avatar answered Apr 03 '26 06:04

Gavriel