I would like to sort alphabetically (case insensitive), the tags choosen from a select2.
I have used the sorter function to sort the tags to be selected but once selected they are not displayed alphabetically.
How to do this ? (I work with last 4.0.13 select2 release).
$('#example1').select2({
tags: true,
multiple: true,
allowClear: true,
sorter: function(data) {
return data.sort(function (a, b) {
var a1 = a.text.toLowerCase();
var b1 = b.text.toLowerCase();
if (a1 > b1) {
return 1;
}
if (a1 < b1) {
return -1;
}
return 0;
});
}
});
<select name="list" id="example1" style="width:500px;">
<option>United States</option>
<option>Austria</option>
<option>Alabama</option>
<option>Jamaica</option>
<option>Taiwan</option>
<option>canada</option>
<option>palau</option>
<option>Wyoming</option>
</select>
Should be Alabama, Austria, Jamaica, United States.
2
Answers
Here’s some working code of what I think you’re looking for,
HTML
JS from, Sorting options elements alphabetically using jQuery
You can use localeCompare function for comparing the strings. Here is the modified code:
It will sort them alphabetically.
Note that: The
United States
word has space in between, so before comparing you have to remove the space between words. You can usereplace()
function for this. Hope it will be helpful.