How to sort the select2 (jQuery plugin) options alphabetically?
Asked Answered
N

4

32

I want to sort the select2 options in alphabetical order. I have the following code and would like to know, how can this be achieved:

<select name="list" id="mylist" style="width:140px;">
   <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>


$('#mylist').select2({
  sortResults: function(results) { return results.sort(); } 
});

I want to sort the data via 'text'.

Northerly answered 27/2, 2015 at 9:56 Comment(0)
P
56

Select2 API v3.x (sortResults)

You can sort elements using sortResults callback option with String.localeCompare():

$( '#mylist' ).select2({
  /* Sort data using localeCompare */
  sortResults: data => data.sort((a, b) => a.text.localeCompare(b.text)),
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.css" integrity="sha256-ijlUKKj3hJCiiT2HWo1kqkI79NTEYpzOsw5Rs3k42dI=" crossorigin="anonymous" /><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.min.js" integrity="sha256-7A2MDY2eGSSUvgfbuH1IdzYk8qkEd3uzwiXADqPDdtY=" crossorigin="anonymous"></script>
<select name="list" id="mylist" style="width:140px;">
   <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>

Select2 API v4.0 (sorter)

You can sort elements using sorter callback option:

$('#mylist').select2({
    sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" integrity="sha256-xqxV4FDj5tslOz6MV13pdnXgf63lJwViadn//ciKmIs=" crossorigin="anonymous" /><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js" integrity="sha256-FA14tBI8v+/1BtcH9XtJpcNbComBEpdawUZA6BPXRVw=" crossorigin="anonymous"></script>
<select name="list" id="mylist" style="width:140px;">
   <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>

Without jQuery

I had another general purpose approach (you can use value or an attribute for sorting elements) without using jQuery:

var select = document.getElementById("mylist");
var options = [];
// Get elements to sort
document.querySelectorAll('#mylist > option').forEach(
  option => options.push(option)
);
// Empty select
while (select.firstChild) {
    select.removeChild(select.firstChild);
}
// Sort array using innerText (of each option node)
options.sort(
  (a, b) => a.innerText.localeCompare(b.innerText)
);
// Add the nodes again in order
for (var i in options) {
    select.appendChild(options[i]);
}
<select name="list" id="mylist" style="width:140px;">
   <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>

With jQuery

Thanks @Narendra Sisodia for jQuery tip:

/* Get options */
var selectList = $('#mylist > option');
/* Order by innerText (case insensitive) */
selectList.sort(
  (a, b) => a.innerText.localeCompare(b.innerText)
);
/* Re-do select HTML */
$('#mylist').html(selectList);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<select name="list" id="mylist" style="width:140px;">
   <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>
Protozoology answered 27/2, 2015 at 11:45 Comment(3)
is there a way to keep the selection order in which the values were selected without sorting the the list?Blende
Are you talking about keeping the original unmodified and an orderly copy?Protozoology
@BalakrishnanBsk, which of the solutions did not work for you? What exact version of jquery and internet explorer do you use? Did you use <meta http-equiv="X-UA-Compatible" content="IE=edge" /> tag? Please, add more information.Protozoology
E
5

Select2 version 4.0 has renamed sortResults to sorter, so you can do:

$('#input').select2({
    sorter: function(data) {
        return data.sort();
    }
})
Exclusive answered 10/8, 2015 at 15:13 Comment(2)
I tried this, but it doesn't sort the initial list, if it's not given in alphabetical order. Plus, I believe you need to give sort a function as parameter that will do the comparison, as @Protozoology has done.Kurzawa
On github.com/select2/select2/issues/3195#issuecomment-256938416 there is a more detailed version which sorts alphabetically and which works in my case.Skees
D
1

Take a look in this code:

$('#your_select').select2({
     /* Sort data using lowercase comparison */
     sorter: data => data.sort((a,b) => a.text.toLowerCase() > b.text.toLowerCase() ? 0 : -1)

});

I hope it has been helped you! =)

Dubbin answered 17/5, 2019 at 13:26 Comment(0)
P
1

This was taken from the github issue, so all credit goes to the original poster, but this is what worked for me.

Version 4.x

$( '#mylist' ).select2({
  sorter: function(data) {
    return data.sort(function (a, b) {
        if (a.text > b.text) {
            return 1;
        }
        if (a.text < b.text) {
            return -1;
        }
        return 0;
    });
  }
});


Pavla answered 8/1, 2020 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.