How to Sort List Items using jQuery with anchors
I have found an interesting jQuery code to sort list items on your web pages and writing this tutorial to apply this functionality in your web projects. In this code snippet we create a jQuery function which load all list items of a given id and match text letters and present you in a sorted form, lets see how it works and its demo with source code.
We use <ul><li>Item</li></ul> lists all the time and implement them in our websites and these lists most of the time unsorted so here is a very simple code snippet to sort these lists with anchors.
HTML List markup
<ul> <li>91</li> <li>28</li> <li>4</li> <li>324</li> </ul> or <ul> <li><a href="https://www.phpgang.com/category/php">PHP</a></li> <li><a href="https://www.phpgang.com/category/jquery">jQuery</a></li> <li><a href="https://www.phpgang.com/category/html">HTML</a></li> <li><a href="https://www.phpgang.com/category/css">CSS</a></li> <li><a href="https://www.phpgang.com/category/mysql">MySQL</a></li> </ul>
Above given lists are un-ordered lists with anchor and without anchor and if you have to sort them usually can do it manually.
jQuery code snippet
<script type="text/javascript"> $(function() { $.fn.sortList = function() { var list = $(this); var items = $("li", list).get(); items.sort(function(a, b) { var listItem1 = $(a).text().toUpperCase(); var listItem2 = $(b).text().toUpperCase(); return (listItem1 < listItem2) ? -1 : 1; }); $.each(items, function(i, itm) { list.append(itm); }); } $("ul#sort").sortList(); }); </script>
Above jQuery code compare each item and change order of each item.
$.fn.sortList = function() create function sortList $(“li”, list).get() get all li items of given id of list, list.append(itm) append items in order $(“ul#sort”).sortList() call function to sort all items of ul with id sort.
That’s all I hope you like this post please comment your feedback.
Tutorial Categories: