0

I have a relatively complex list used as a product comparison table and need the list to be sortable by each of the list-items various attributes. Seems like this should be simple, but I haven't been able to get anything to work.

So I have something like this:

<ul id="myList">

   <li id="item1">
     <div class="myListTitle">Item 1</div>
     <div class="myListPrice">
       <span class="currency">£</span><span class="digits">12.45</span></div>
     <div class="myListFirstFeature">456</div>
     <div class="myListLastFeature"><span class="digits">36</span> options</div>
   </li>

   <li id="item2">
     <div class="myListTitle">Item 2</div>
     <div class="myListPrice">
       <span class="currency">£</span><span class="digits">9.30</span></div>
     <div class="myListFirstFeature">241</div>
     <div class="myListLastFeature"><span class="digits">12</span> options</div>
   </li>

    <li id="item3">
     <div class="myListTitle">Item 3</div>
     <div class="myListPrice">
       <span class="currency">£</span><span class="digits">17.25</span></div>
     <div class="myListFirstFeature">842</div>
     <div class="myListLastFeature"><span class="digits">64</span> options</div>
   </li>  </ul>

etc.

And then I want to have buttons that will order the list by the various attributes, ie

<button id="orderByPrice">Price</button>
<button id="orderByFirstFeature">1st Feature</button>
<button id="orderByLastFeature">Last Feature</button>

I hope that makes sense. Any help much appreciated.

Thanks

  • You can use [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to achieve this. – Rory McCrossan Dec 06 '15 at 18:03
  • http://stackoverflow.com/questions/21600802/jquery-sort-list-based-on-data-attribute-value . You are trying something similar to this – akgaur Dec 06 '15 at 18:05

1 Answers1

1

You can use sort() to achieve this. By providing a function to that method you can define the logic you want to sort by. If you include a data-* attribute on the button to determine what you are attempting to sort by, you can use a switch statement within that function to find the value to sort by. Try this:

$('.sort').click(function() {
  sortLi($(this).data('order'));
});

function sortLi(order) {
  var fieldClass = order == 'price' ? '.myListPrice .digits' : order == 'first-feature' ? '.myListFirstFeature' : '.myListLastFeature .digits';
  $('#myList li').sort(function(a, b) {
    var aValue = parseFloat($(a).find(fieldClass).text());
    var bValue = parseFloat($(b).find(fieldClass).text());
    if (aValue > bValue)
      return 1;
    if (aValue < bValue)
      return -1;
    return 0;
  }).appendTo('#myList');
}

Example fiddle

More information on sort() at MDN

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • This was great, very helpful. However I eventually managed to get it working using this: http://www.listjs.com/ – JakeTibbits Jan 14 '16 at 17:17