How to sort a combo select by the text of options?

Asked

Viewed 3,250 times

2

I wish to sort a select combo from HTML in alphabetical order and would like help in logic to be able to assemble a function that does this regardless of the number of elements.

2 answers

4


function NASort(a, b) {    
    if (a.innerHTML == 'NA') {
        return 1;   
    }
    else if (b.innerHTML == 'NA') {
        return -1;   
    }       
    return (a.innerHTML > b.innerHTML) ? 1 : -1;
};

$('select option').sort(NASort).appendTo('select');


<select>
    <option value="1">Car</option>
    <option value="2">Bus</option>
    <option value="3">NA</option>
    <option value="4">Bike</option>
    <option value="5">Tractor</option>
    <option value="6">NA</option>
    <option value="7">A</option>
</select>

Jsfiddle

Source

3

You can use the Array.prototype.sort():

function ordenar() {
    var itensOrdenados = $('#itens option').sort(function (a, b) {
        return a.text < b.text ? -1 : 1;
    });

    $('#itens').html(itensOrdenados);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="itens">
    <option value="2">Maçã</option>
    <option value="1">Banana</option>
    <option value="3">Laranja</option>
    <option value="8">Uva</option>
    <option value="5">Amora</option>
    <option value="15">Melão</option>
</select>
<button onclick="ordenar()">Ordenar</button>

  • Hello, thanks for the answer, although the topic is old, helped me a lot! Only one thing: in this example, the value that appears to the user after the ordering is the last one on the list ("Grape", in this case). How to do for the value to appear after the ordination is first ("Amora", in this case)?

  • Just reverse the function’s return value sort : return a.text < b.text ? 1 : -1;.

Browser other questions tagged

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