Sorting an ordered list with jQuery
Posted by Sem Dendoncker on February 8th, 2010I had the following problem lately.
I had a rather long ordered list.
But everytime I wanted to add an item I had to manually check were to put it.
Well then I asked a colleague of mine if there wasn’t a way to do this with javascript and he came up with the following solution:
<html>
<head>
<title>sort ol</title>
</head>
<body>
<ol id="tobesorted">
<li>c</li>
<li>b</li>
<li>a</li>
<li>A</li>
<li>C</li>
<li>A</li>
<li>B</li>
<li>a</li>
<li>A</li>
<li>a</li>
<li>banaan</li>
<li>aardbei</li>
<li>sinaasappel</li>
<li>citroen</li>
<li>appel</li>
<li>peer</li>
</ol>
<script src="jquery-1.4.min.js"></script>
<script>
jQuery.fn.sort = function() {
return this.pushStack(Array.prototype.sort.apply(this, arguments), []);
};
function sortAlpha(a, b) {
var atext = a.innerHTML;
var btext = b.innerHTML;
var alower = atext.toLowerCase();
var blower = btext.toLowerCase();
return alower > blower ? 1 : (
alower < blower ? -1 : (
atext > btext ? 1 : (
atext < btext ? -1 : 0
)
)
);
};
$(document).ready(function() {
$('#tobesorted li').sort(sortAlpha).appendTo('#tobesorted');
});
</script>
</html>
This way a list looking like this:
- banaan
- aardbei
- sinaasappel
- citroen
- appel
- peer
now looks like this:
- aardbei
- appel
- banaan
- citroen
- peer
- sinaasappel
Sorry for the dutch words but hey, it’s just an alphabet.
This solution also works for an un-ordered list.
Special thanks to Crydust
I hope others will find this post helpfull.
Cheers,
Mayiko
Recent Comments