Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Jquery sort data in select

I have written the following code which is working when there is alphabetic data, how can I make it work uniquely irrespective of alphabets or numbers

function sortList(selectId) {
  var options = $(selectId + ' 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);
  });
}
$(document).ready(function() {
  sortList("#whatever");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='whatever'>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='10'>10</option>
</select>

It is getting sorted as 1,10,2 where I am looking it like 1,2,10. How to make this function unique to work for all scenarios

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This question is a duplicate of How can I sort elements by numerical value of data attribute?
Here's a snippet with the answer modified from that question to match this question

var element = $("#whatever");
element.find("option").sort(function(a, b) {
    return +a.getAttribute('value') - +b.getAttribute('value');
}).appendTo(element);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='whatever'>
    <option value='1'>1</option>
    <option value='6'>6</option>
    <option value='9'>9</option>
    <option value='3'>3</option>
    <option value='10'>10</option>
</select>

I just copied my snipped to your jsfiddle and it worked Here it is https://jsfiddle.net/g3cjbzey/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda