1

Her is my html and jQuery. I want the ability to sort them alphabetic by class name when I press the "Sort" "button" in the filter div. Right now I can hide all others by "green" all others will hide. But but I need the ability to sort them.

    <div id='filters'>
        <a href='#' id ="sort">Sort</a> 
        <a href='#' id='blue'>blue</a>
        <a href='#' id='green'>green</a>
        <a href='#' id='yellow'>yellow</a>
    </div

    <div id="box">
        <ul id="filter">
            <li class="green"></li>
            <li class="blue"></li>
            <li class="yellow"></li>
            <li class="blue"></li>
            <li class="yellow"></li>
        </ul> 
    </div>

$('#filters a').click(function(e){ 
    e.preventDefault();  
    var filter = $(this).attr('id');  
        $('#box ul li').show();  
        $('#box ul li:not(.' + filter + ')').hide();  
});  
user2064285
  • 43
  • 1
  • 1
  • 6

1 Answers1

0

This sorts the list in ascending order:

 <div id='filters'>
    <a href='#' id ="sort">Sort</a> 
    <a href='#' id='blue'>blue</a>
    <a href='#' id='green'>green</a>
    <a href='#' id='yellow'>yellow</a>
</div>

<div id="box">
    <ul id="filter">
        <li class="green">Green</li>
        <li class="blue">Blue</li>
        <li class="yellow">Yellow</li>
        <li class="blue">Blue</li>
        <li class="yellow">Yellow</li>
    </ul> 
</div>

$('#filters a').click(function(e){ 

  e.preventDefault();  

  var filter = $(this).attr('id'); 

  if (filter == "sort") {

    $('#box ul li').sort(asc_sort).appendTo('#filter');
  }
  else {

    $('#box ul li').show();  
    $('#box ul li:not(.' + filter + ')').hide(); 

  }
});

function asc_sort(a, b) { 
    return ($(b).text()) < ($(a).text());
}

JSFiddle

Full disclosure: I used the code found in this question.

If you were to extend this to have the list sort alternatively ascending and descending, you'd probably just need either a variable to track what order the list is currently in, otherwise a check to see if the list is currently in ascending order, then sort descending, and vice versa.

Community
  • 1
  • 1
shauneba
  • 2,122
  • 2
  • 22
  • 32