How to display a page with a sorted drop down list?

12,526

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);
    });
}
Share:
12,526
user2473532
Author by

user2473532

Updated on June 04, 2022

Comments

  • user2473532
    user2473532 almost 2 years

    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!