sort select options alphabetically javascript code example

Example 1: jquery sort select options by text

function alphabetizeList() {
    var sel = $(listField);
    var selected = sel.val(); // cache selected value, before reordering
    var opts_list = sel.find('option');
    opts_list.sort(function (a, b) {
        return $(a).text() > $(b).text() ? 1 : -1;
    });
    sel.html('').append(opts_list);
    sel.val(selected); // set cached selected value
}

alphabetizeList('#FIELDID');

Example 2: html reorder list aaccording

function sortMeBy(arg, sel, elem, order) {
        var $selector = $(sel),
        $element = $selector.children(elem);
        $element.sort(function(a, b) {
                var an = parseInt(a.getAttribute(arg)),
                bn = parseInt(b.getAttribute(arg));
                if (order == "asc") {
                        if (an > bn)
                        return 1;
                        if (an < bn)
                        return -1;
                } else if (order == "desc") {
                        if (an < bn)
                        return 1;
                        if (an > bn)
                        return -1;
                }
                return 0;
        });
        $element.detach().appendTo($selector);
}
/* arg : The data-filter to parse for sorting. In our case it would be “data-category”
sel : This will be the parent selector that contains the data filter. In our case it is the class “search-results”
elem : This further narrows down the child elements within the parent selector, which is just a “li” in this case
order : This specifies the sort order. “asc” or “desc” would either be acceptable *\

Tags:

Html Example