Lioo
Lioo

Reputation: 395

Sorting and Formatting with TableSorter

I'm trying to format some data of a table that is constantly updated by ajax.

I want that the float data become this

1.100.500,00 (currency)

after I sort it.

The problem is that tablesorter only sorts the float values correctly if they are in the first format. What I need to do is:

  1. When ajax loads the data, show it like (currency), as currency.
  2. When a table <th> is clicked to sort data, remove the (currency) currency format and sort the data correctly.
  3. After sorted correctly, re-format the data like (currency), as currency.

I already tried this:( that I've found that it's the solution to many questions here in SO)

$.tablesorter.addParser({ 
        // set a unique id 
        id: 'thousands',
        is: function(s) { 
            // return false so this parser is not auto detected 
            return false; 
        }, 
        format: function(s) {
            // format your data for normalization 
            return s.replace('.','').replace(/,/g,'');
        }, 
        // set type, either numeric or text 
        type: 'numeric' 
        }); 


        $("#table_1").tablesorter({
            headers: {
                2: {//zero-based column index
                    sorter:'thousands'
                }
            }
    });

but it's not working.

Upvotes: 1

Views: 375

Answers (1)

Mottie
Mottie

Reputation: 86433

There are four things that fixing (demo):

  1. The function to replace periods will only remove one. So change it to .replace(/\./g, "") (the period needs to be escaped as well).
  2. Remove the $ from the string
  3. Replace the , with a decimal point, so the value gets parsed correctly.
  4. Convert the value from a string to a number using the built-in $.tablesorter.formatFloat function.

    $.tablesorter.addParser({
      id: 'thousands',
      is: function(s) {
        return false;
      },
      format: function(s) {
        var number = s.replace(/\$/g, '').replace(/\./g, '').replace(/,/g, '.');
        return $.tablesorter.formatFloat(number);
      },
      type: 'numeric'
    });
    $(function() {
      $("table").tablesorter({
        theme: 'blue',
        headers: {
          0: {
            sorter: 'thousands'
          }
        }
      });
    });
    

The demo I shared is using my fork of tablesorter, but the code will also work as expected in the original version.

Upvotes: 1

Related Questions