3

I have a select list

<select id="select_zone">
  <option value="north">North</option>
  <option value="east">East</option>
  <option value="south">South</option>
  <option value="west">West</option>
</select>

Now I want the items in the list to appear in a sorted manner using jquery. I should be able to add items in the list in the html code manually (in a random order). BUT they should appear alphabetically sorted in the browser page.

I have been breaking my head and have done a lot of R&D. But not being able to find a way to sort the dropdpwnlist at the time the page is loaded. Please help!

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
user2473532
  • 49
  • 1
  • 1
  • 4
  • did you look at this? http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/ – CodeToad Jun 11 '13 at 09:39
  • possible duplicate of [Sorting options elements alphabetically using jQuery](http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery) - I thought you did research? – George Jun 11 '13 at 09:39
  • Possible duplication of SO http://stackoverflow.com/questions/2048762/sort-items-in-a-dropdown-list-without-the-first-item – dreamweiver Jun 11 '13 at 09:41
  • My Code is still not working. I am new to jquery. Please could anyone provide a step by step procedure. – user2473532 Jun 11 '13 at 11:24

3 Answers3

8

here is a working fiddle using code from : http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/

http://jsfiddle.net/Rz6xv/

code:

function sortDropDownListByText() {
    // Loop for each select element on the page.
    $("select").each(function() {

        // Keep track of the selected option.
        var selectedValue = $(this).val();

        // Sort all the options by text. I could easily sort these by val.
        $(this).html($("option", $(this)).sort(function(a, b) {
            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));

        // Select one option.
        $(this).val(selectedValue);
    });
}
Jim
  • 22,354
  • 6
  • 52
  • 80
CodeToad
  • 4,656
  • 6
  • 41
  • 53
0

write a method and call on document ready()

function sortMycombo() {
   $("#select_zone").html($('#select_zone option').sort(function(x, y) {
         return $(x).text() < $(y).text() ? -1 : 1;
   }))
   $("#select_zone").get(0).selectedIndex = 0;
   e.preventDefault();
});
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

You could use jQuery and something like this:

$("#id").html($("#id option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
DevZer0
  • 13,433
  • 7
  • 27
  • 51