Sorting select in alphabetical order with jQuery

3

I need to sort select alphabetically.

I tried to use this function that I found on the internet

function ordenarSelect(){   
    f$(".slc_Reuniao").html($("option", $(".slc_Reuniao")).sort(function(a,b){
        return a.text == b.text  ? 0 : a.text < b.text ? -1 : 1;
    }));
};

My initial select is:

 <select class="slc_Reuniao">
    <option value="SO" selected>--</option>             
 </select>

After a function that dynamically adds with append the names returned from query . I need to sort them out.

But it is not working, on the contrary it is generating new options , I am using IndexedDB as a database it is also based on javascript, I tried to look for something that at the moment I am searching the data in the database, but I do not find anything about it. How do I do this?

  

On the same page I have 3 select whose content is equal.

TheformofimplementationiswhenIclickonamenulocatedinasidemenu,triggersaneventthatIdescribebelow.

$(document).on("click", "#cadReu", function(evt)
{
    var w_codigo_turma = sessionStorage.getItem('codigo');
    carregaSelectAluno(w_codigo_turma);
    ordenarSelect();
    activate_page("#cadastro_REUNIAO");
});

   $( ".slc_Reuniao" ).each(function() {
      $(this).append(HTMLNovo);
    }); 

After this I call the function sql which is where I am putting the functions indicated by the answers of my question. Both tips are giving same problem. It's not organizing and it's working. One problem I identified is that when I come back it adds the names again.

    
asked by anonymous 25.09.2015 / 13:48

3 answers

6

You can extract the values of each option into a array , sort the values, and afterwards, update your select . It would look like this:

$( document ).ready(function() {   
    var n;
    var selects = $('select.slc_Reuniao');
  //console.log(selects);
    for(n = 0; n < selects.length; n++){
      var options = $('select.slc_Reuniao:eq('+n+') option');
       //console.log(opt);
      var arr = options.map(function(_, o) {
        return {
            t: $(o).text(),
            v: o.value
        };
    }).get();
    arr.sort(function(o1, o2) {
        return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
    });
    options.each(function(i, o) {
        console.log(i);
        o.value = arr[i].v;
        $(o).text(arr[i].t);
    });
  

}
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectclass="slc_Reuniao">
    <option value='PA'>Para</option>
    <option value='BA'>Bahia</option>
    <option value='MG'>Minas Gerais</option>
    <option value='ES'>Espirito Santo</option>
    <option value='PE'>Pernanbuco</option>
 </select>

 <select class="slc_Reuniao">
    <option value="SP">São Paulo</option>  
    <option value='RJ'>Rio de Janeiro</option>
    <option value='TO'>Tocantins</option>
    <option value="AC">Acre</option>  
    <option value='BA'>Bahia</option>
 </select>

 <select class="slc_Reuniao">
    <option value='BA'>Bahia</option>
    <option value="AC">Acre</option>  
    <option value='TO'>Tocantins</option>
    <option value='SC'>Santa Catarina</option>
    <option value='PA'>Para</option>
 </select>

Edit

To sort by loading the page, simply place the function inside $ (Document) .ready () that it will call the function once your page is ready. It would look like the code.

$( document ).ready(function() {   
    var n;
    var selects = $('select.slc_Reuniao');
  //console.log(selects);
    for(n = 0; n < selects.length; n++){
      var options = $('select.slc_Reuniao:eq('+n+') option');
       //console.log(opt);
      var arr = options.map(function(_, o) {
        return {
            t: $(o).text(),
            v: o.value
        };
    }).get();
    arr.sort(function(o1, o2) {
        return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
    });
    options.each(function(i, o) {
        console.log(i);
        o.value = arr[i].v;
        $(o).text(arr[i].t);
    });


}
 });

See an example in JSFiddle.

Source: Sorting Options - SOen.

    
25.09.2015 / 14:09
3

Try the following:

var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
  o.value = arr[i].v;
  $(o).text(arr[i].t);
});

Example: link

    
25.09.2015 / 14:05
2

Use this function to sort your select

function ordenarSelect(id_componente)
{
  var selectToSort = jQuery('#' + id_componente);
  var optionActual = selectToSort.val();
  selectToSort.html(selectToSort.children('option').sort(function (a, b) {
    return a.text === b.text ? 0 : a.text < b.text ? -1 : 1;
  })).val(optionActual);
}




$(document).ready(function () {
  ordenarSelect('idMeuSelect');
});

Example:

function ordenarSelect(id_componente)
    {
      var selectToSort = jQuery('#' + id_componente);
      var optionActual = selectToSort.val();
      selectToSort.html(selectToSort.children('option').sort(function (a, b) {
        return a.text === b.text ? 0 : a.text < b.text ? -1 : 1;
      })).val(optionActual);
    }
    $(document).ready(function () {
      ordenarSelect('meuSelect');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="meuSelect">
    <option>Maria</option>
    <option>Pedro</option>
    <option>Zico</option>
    <option>Ana</option>
     <option>---</option>
    <option>Paulo</option>
  </select>
    
25.09.2015 / 14:14