Michael St Clair
Michael St Clair

Reputation: 6635

Using jQuery to sort li

I have this script that I use to sort a list of li's, however it is not working when there is more than one digit, it is sorting with the first digit taking preference, so 10 comes before 2. Is there a way to modify this so it sorts it based on the numeric value?

jQuery.fn.sortDomElements = (function() {
    return function(comparator) {
        return Array.prototype.sort.call(this, comparator).each(function(i) {
              this.parentNode.appendChild(this);
        });
    };
})();

$("#sortable3, #sortable4").children().sortDomElements(function(a,b){
    akey = $(a).attr("sortkey");
    bkey = $(b).attr("sortkey");
    if (akey == bkey) return 0;
    if (akey < bkey) return -1;
    if (akey > bkey) return 1;
});

Upvotes: 0

Views: 60

Answers (2)

Mark
Mark

Reputation: 92471

You're comparing strings. When comparing strings you get this:

"10" <  "2"
true

Instead force the string to ints base 10:

parseInt("10", 10) <  parseInt("1", 10)
false

Trying this:

$("#sortable3, #sortable4").children().sortDomElements(function(a,b){
    akey = parseInt(($(a).attr("sortkey"), 10);
    bkey = parseInt($(b).attr("sortkey"), 10);
    if (akey == bkey) return 0;
    if (akey < bkey) return -1;
    if (akey > bkey) return 1;
});

should fix it.

Upvotes: 2

creativekinetix
creativekinetix

Reputation: 397

Try converting the key to a number.

akey = parseInt($(a).attr("sortkey");
...

Upvotes: 1

Related Questions