Wednesday, April 18, 2012

Sorting an unordered list in javascript


In one of my recent project I come  across sorting  an unordered list on client side without post backing the whole page.The below code snippet will explain the logic to sort the unordered list(ul) using java-script.

The below code snippet is tested and it works fine.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function sortUnorderedList(ul, sortDescending) {
            //if (typeof ul == "String")
            ul = document.getElementById(ul);

            // Idiot-proof, remove if you want
            if (!ul) {
                alert("The UL object is null!");
                return;
            }

            // Get the list items and setup an array for sorting
            var lis = ul.getElementsByTagName("li");
            var vals = [];

            // Populate the array
            for (var i = 0, l = lis.length; i < l; i++)
                vals.push(lis[i].innerHTML);

            // Sort it
            vals.sort();

            // Sometimes you gotta DESC
            if (sortDescending)
                vals.reverse();

            // Change the list on the page
            for (var i = 0, l = lis.length; i < l; i++)
                lis[i].innerHTML = vals[i];
        }
    </script>
</head>
<body>
    <div>
        <ul id="sortlist">
            <li>apple</li>
            <li>banana</li>
            <li>car</li>
            <li>dog</li>
        </ul>
        <button id="btn" value="ASort" onclick="sortUnorderedList('sortlist',false)">
           Ascending</button>
    <button id="Button1" value="DSort" onclick="sortUnorderedList('sortlist',true)">
        Descending</button></div>
</body>
</html>


References - http://stackoverflow.com/questions/9868375/sorting-columns-inside-a-list-alphabetically-using-jquery