Search code examples
jquerysortinglocalecurrency

Sorting List Items in European Currency Format


I'm currently making a page with loads of products on, which need to be sorted by name, popularity and price.

I'm using the tinySort plugin, which has worked perfectly on locales that use a decimal point in their currency, but it's not working so well in European locales that format their price as '12,95 €'

Basically, I need a function that converts the price attribute into a number which is sortable.

Each box uses the following code

<li class="box" id="234860200" >
    <img src="#" alt="" class="packshot" title="">
    <p class="productTitle"></p>
    <div class="bottomAlign">
    <p><span class="price"></span> <span class="strikethrough strikeOFF"></span></p>

    <input id="" type="checkbox" name="product" data-price="" class="calculation-item" value=""/>
<label for="" class="calculation-label"><span class="checkboxTitle"></span><span class="defaultAdd">Add to Basket</span></label>
    </div>
    <div class="clear"></div>                     
</li>

The sorting button uses the following js

function priceLow() {
    $('ul#productList>li').tsort('span.price');
}

If anyone could help me, that would be amazing.


Solution

  • This should do it:

    function priceLow() {
        $('ul#productList>li').tsort('span.price',
          {
             sortFunction: function(a,b) {
               var a_val = parseFloat(a.s.replace(/,/, "."));
               var b_val = parseFloat(b.s.replace(/,/, "."));
    
               return (a_val==b_val) ? 0 : ((a_val>b_val) ? 1 : -1);
             }
          }
        );
    }