Sort a list

Sort a list

Some time back I was looking for a sort rutine and I did not want to build a simple bobble sort my self. JQuery is smart, how the hell do I get it to help me sort a UL list for me.

The anwser came to me from the web after searching and reading many web pages.
I found one that gave me a idea on how to make a fast and easy to implante for any thing.

Bill Richards gave me the solution on his BLOG

JS
    <script type="text/javascript">
      jQuery.fn.sort = function() {
         return this.pushStack( [].sort.apply( this, arguments ), []);
       };
      
      function sortAlpha1(a,b){
          return a.innerHTML > b.innerHTML ? 1 : -1;
      };
      function sortAlpha2(a,b){
          return $('div', a).attr('id') * 1 > $('div', b).attr('id') * 1 ? 1 : -1;
      };
      function sortAlpha3(a,b){
          return $('span', a).text() > $('span', b).text() ? 1 : -1;
      };
      
      $(function() {
         $('a#sortList1').click(function() {
            $('#caseListing li').sort(sortAlpha1).appendTo('#caseListing');
            return false;
         });
         $('a#sortList2').click(function() {
            $('#caseListing li').sort(sortAlpha2).appendTo('#caseListing');
            return false;
         });
         $('a#sortList3').click(function() {
            $('#caseListing li').sort(sortAlpha3).appendTo('#caseListing');
            return false;
         });
      });
    </script>


HTML
<body>
<a href="#" id="sortList1">Sort List option 1</a> <a href="#" id="sortList2">Sort List option 2</a> <a href="#" id="sortList3">Sort List text</a><br />
<br />
<ul id="caseListing">
   <li>
      <div id="1">
         <a href="/Cases/Show/1">Case 1</a> : <span>Some search help</span>
      </div>
   </li>
   <li>
      <div id="3">
         <a href="/Cases/Show/3">Case 3</a> : <span>Ahhh... No good</span>
      </div>
   </li>
   <li>
      <div id="6">
         <a href="/Cases/Show/6">Case 6</a> : <span>This will be last after search</span>
      </div>
   </li>
   <li>
      <div id="10">
         <a href="/Cases/Show/10">Case 10</a> : <span>Or not</span>
      </div>
   </li>
</ul>

</body>


I have 3 defrent sort at the start. The first works on innerHTML for the LI item. It's not so good as it will have 10 < 1 so I made solution nr 2. Get the ID from from the DIV I am using and multiply it by 1 so it convert it to a number (Strange I can not use the parseint() javascript function)
So what about option 3. Well I needed at function to make a sort on the text in the list. I came up with putting the text inside a span and sort the list after it.
    • Topic Participants

    • bhe