How to sort a select combo by the options text?

1

I want to sort a select combo from HTML alphabetically and would like help with logic to get a function to do that, regardless of the number of elements.

    
asked by anonymous 18.05.2015 / 16:01

2 answers

3
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

    
18.05.2015 / 16:36
2

You can use 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><selectid="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>
    
18.05.2015 / 16:41