-4

i have a select option

<select>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>bbb</option>
</select>

How to sort them. so output will

aaa
bbb
ccc
ddd

this question is asked to me in an interview answer if any Know Thanks In advance

laaposto
  • 11,377
  • 15
  • 52
  • 68

3 Answers3

4

You can use use JavaScript sort method. It sorts the elements in lexical order. So you can set the innerHTML of the select element based on the result of the sort function.

Read more about the sort function here

Try:

$("select").html($('select option').sort(function (x, y) {

    return $(x).text() < $(y).text() ? -1 : 1;

}))

DEMO

laaposto
  • 11,377
  • 15
  • 52
  • 68
0

Add an id

<select id='myselect'>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>bbb</option>
</select>

Get all options in an array, sort it and then change the values of the select

var array = new Array();
$("#myselect option").each(function() { array.push($(this).text()) });
array.sort();

$("#myselect option").each(function(index,elem) { $(this).html(array[index]) });
Alexandru Chichinete
  • 1,169
  • 12
  • 23
0

Working Fiddle

$('#sort').click(function () {
$('select').each(function () {
   var options = $(this).children('option');
    options.sort(function (optionA, optionB) {
        return optionA.value.localeCompare(optionB.value);
    });
    $(this).empty().append(options);
});
});
Suhas Gosavi
  • 2,090
  • 17
  • 39