Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'.

like image 524
Raju28 Avatar asked Feb 27 '15 09:02

Raju28


People also ask

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

Is Select2 a plugin?

This POC is intended to illustrate Select2, a JQuery Plugin which is used as a replacement for select box with support for searching, tagging, remote data sets, infinite scrolling and many other highly used options and contains event handling.

Is Select2 JQuery?

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.


1 Answers

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>
like image 179
OscarGarcia Avatar answered Oct 26 '22 08:10

OscarGarcia