bala3569
bala3569

Reputation: 11010

Sorting a listview using jQuery?

Here the code is only sorting the li items in ascending order.How to sort in both ascending and descending order by using this code Sorting <li> tags

 function sort(list, key) {
         $($(list).get().reverse()).each(function (outer) {
             var sorting = this;
             $($(list).get().reverse()).each(function (inner) {
                 if ($(key, this).text().localeCompare($(key, sorting).text()) > 0) {
                     this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
                 }
             });
         });
     }

and

window.onload = function () {
         var desc = false;
         document.getElementById("stCodeDSC").onclick = function () {
             //             sortUnorderedList("list3", desc);

             sort('ul.conn1>li', 'td.code1');
             desc = !desc;
             return false;
         }

Any suggestion?

EDIT: If i give <0 then it is sorting in descending order..

EDIT2:

$(document).ready(function() {
         var desc = false;
         document.getElementById("stCodeDSC").onclick = function () {
             //             sortUnorderedList("list3", desc);

             sort('ul.conn>li', 'td.code');

             desc = !desc;
             return false;
         }
         document.getElementById("stNameDSC").onclick = function () {
             //             sortUnorderedList("list3", desc);

             sort('ul.conn>li', 'td.name');
             desc = !desc;
             return false;
         }
     });

Upvotes: 0

Views: 981

Answers (1)

Tomalak
Tomalak

Reputation: 338178

How about a jQuery plugin:

function elemLocaleCompare(left, right) {
    return $(left).text().localeCompare($(right).text());
}

$.fn.extend({
    sortList: function(order) {
        return this.each(function() {
            var $list = $(this),
                li = $list.children("li").toArray().sort(elemLocaleCompare);

            if (li.length == 0) return true;

            order = order || $list.data("nextOrder") || "asc";

            if (order == "asc")
                $list.append(li).data("nextOrder", "desc");
            else
                $list.append(li.reverse()).data("nextOrder", "asc");
        });
    }
});

Use like:

$("ol").sortList("asc");

// or...
$("#someList").sortList();  // initial sort order, "asc" is default

$("#someButton").click(function () {
  $("#someList").sortList();     // no argument -> toggle sort order
});
​

Upvotes: 1

Related Questions