Ordering select in alfábetica order with jQuery

Asked

Viewed 3,091 times

3

I need to order a select alphabetically.

I tried to use this function 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>

I run a function that adds dynamically with append the names that came back from query. I must order them.

However it is not working, on the contrary it is generating new options, am using IndexedDB as database it is also based on javascript, I tried to search for something that at the moment I am searching the data in the database I sort itself as in the sql but I couldn’t find anything about it. How should I do this ?

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

Select gerando ao fazer o que me indicaram

The implementation way is when I click on a menu located in a sidemenu, triggers an event that I describe below.

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

After it calls the function carregarSelectAluno(), I won’t add by size but its function is just to create the <option value""></option> and add in the field where caught by the command $wrapper = document.querySelector('.slc_Reuniao'); and put in select this way

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

After this I call the function ordenarSelect() which is where I am placing the functions indicated by the answers to my question. Both tips are giving same problem. It is not organizing and it is conducting. A problem I identified that is when I return it adds the names again.

3 answers

6


You can extract the values from each option in a array, order the values and after, update your select. That would be your 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);
    });
  

}
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="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 when loading the page, just put the function inside the $ (Document) . ready () that it will call the function as soon as your page is ready. That would be 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.

  • I wanted something dynamic that didn’t need to add events to clicks,

  • I edited the answer, see if it helps you

  • My friend, the method indicated for you is giving something interesting, when I go on the page it performs only 4 changes, if I go out and enter the page it does with all the options of select but it blocks 3 previous select and the last only that is working. in the log gave the following result.Montagem dos selects concluido com sucesso. main.js:29&#xA;0 &#xA;1 &#xA;2 &#xA;3 &#xA;Montagem dos selects concluido com sucesso. main.js:29&#xA;0 &#xA;1 &#xA;2 &#xA;3 &#xA;4 &#xA;5 &#xA;6 &#xA;7 &#xA;8 &#xA;9 &#xA;10&#xA;11&#xA;12&#xA;13&#xA;14&#xA;15

  • I didn’t understand the editions of your question. You own several select's and want to sort everyone when accessing the page, or want to sort after some interaction, or both options?

  • No, I need to order all select when accessing the page, in fact I ride it disorderly and I want to order and send to page.

  • You can change your answer to suit ?

  • @Renanrodrigues I edited the answer again. Check if this is what you want.

  • Something crazy is happening, it just takes the first field of select and how it is outro it does not organize. I am calling the function as soon as I have just put everything in select. What may be happening ? What is my mistake ?

Show 3 more comments

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: http://jsfiddle.net/Pointy/trELD/

  • This method did not work.

  • How you are implementing?

  • edited my question see la

  • Do the following, first include the disordered options and then run the function I passed in my example

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>
  <select id="meuSelect">
    <option>Maria</option>
    <option>Pedro</option>
    <option>Zico</option>
    <option>Ana</option>
     <option>---</option>
    <option>Paulo</option>
  </select>

  • This method did not work.

  • I added an example, note that it is working. Any doubt just ask. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.