Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - TableSorter custom parser not working

Here is my custom parser:

$.tablesorter.addParser({
    id: "customParser",
    is: function (stringValue) {
        return false;
    },
    format: function (stringValue) {
        var stringValueParts = stringValue.split("-");
        var numericPartOfStringValue = parseInt(stringValueParts[2]);
        return numericPartOfStringValue ;
    },
    type: 'numeric'
});

stringValue will have values like:

  • ABC-DE-1
  • ABC-DE-10
  • ABC-DE-100
  • ABC-DE-101
  • ABC-DE-1000

Here is the code where I set-up the tablesorter and added the custom sort parser:

$(function() {
    $("#dataTable").tablesorter({
        headers: {
            3: {
                sorter: 'customParser'
            }
        }
    });
});

I did add a console.log(numericPartOfStringValue) and all of the numbers were written out to the console so it seems like the parser is doing what it should be doing.

So what do I want to happen?

I want my values to be sorted on the numeric part of the string as below:

  • ABC-DE-1
  • ABC-DE-10
  • ABC-DE-100
  • ABC-DE-101
  • ABC-DE-1000

What is actually happening?

The values are being sorted in this way:

  • ABC-DE-1
  • ABC-DE-10
  • ABC-DE-100
  • ABC-DE-1000
  • ABC-DE-101

What else did I try?

I added the following to my html but it didn't make a difference:

<th class="{sorter: 'CustomParser'}">
    String Value Column
</th>

And finally:

Here is an example value from the table cell:

<td>
    <span class="badge">ABC-DE-1</span>
</td>
like image 241
carey walker Avatar asked Oct 20 '22 23:10

carey walker


1 Answers

Its working, you just need to set the default sort order. I used sortList. which is an array of tuples which contain the th-index and the order (asc=0, desc=1).

Working fiddle:

 $("#dataTable").tablesorter({
     sortList: [[0,0]],   
     headers: {
            0: {
                sorter: 'customParser'
            }
        }
    });
like image 52
Nix Avatar answered Nov 17 '22 09:11

Nix