Saltar al contenido

¿Cómo ordenar alfabéticamente las opciones de select2 (complemento jQuery)?

Solución:

Select2 API v3.x (sortResults)

Puede ordenar elementos usando sortResults opción de devolución de llamada con 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)

Puede ordenar elementos usando sorter opción de devolución de llamada:

$('#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>


Sin jQuery

Tuve otro enfoque de propósito general (puede usar un valor o un atributo para ordenar elementos) sin usar 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>

Con jQuery

Gracias @Narendra Sisodia por el consejo de jQuery:

/* 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>

Select2 versión 4.0 ha cambiado de nombre sortResults para sorter, para que pueda hacer:

$('#input').select2({
    sorter: function(data) {
        return data.sort();
    }
})
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *