0

I have a table which contains column of Capacities like this :

<table id="datatable" class="display" width="100%">
    <thead>
        <tr>
            <th>Col1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>2 Go</td>
        </tr>
        <tr>
            <td>1 To</td>
        </tr>
        <tr>
            <td>320 Go</td>
        </tr>
        <tr>
            <td>2 To</td>
        </tr>
        <tr>
            <td>500 Go</td>
        </tr>
    </tbody>
</table>

I'm trying to use jQuery dataTable to sort the column to produce the following:

2 Go
320 Go
500 Go
1 To
2 To

but can't figure out how to do it from reading the sorting and plugins docs.

I tried this solution, but can't make it work.

Community
  • 1
  • 1
Liza
  • 197
  • 1
  • 15

2 Answers2

0

My untested suggestion using a modified version of the code you referenced would be to strip the ' Go' and ' To' text from the data you are comparing and at the same time add 1 million to the numbers that end with ' To'.

Note: I used one million assuming that NNN Go/To would never be >= one million.

jQuery.extend( jQuery.fn.dataTableExt.oSort, { "capacity-pre": function ( a ) {

// Remove ' To' and add 1 million to the number:
var x = String(a).replace(/ To/g, "1000000"); 

// Just remove the text ' Go'
x = String(a).replace(/ Go/g, "") 

// now we are just returning a number to do your sorting comparisons against
return parseFloat( x ); 

},

"capacity-asc": function ( a, b ) { return ((a < b) ? -1 : ((a > b) ? 1 : 0)); },

"capacity-desc": function ( a, b ) { return ((a < b) ? 1 : ((a > b) ? -1 : 0)); }

Then in the datatable, set the type to capacity

$('table').dataTable({ "aoColumns": [{ "sType": "capacity" }], "aaSorting": [[ 0, "desc" ]], });

Drew
  • 4,215
  • 3
  • 26
  • 40
0

You can try this. Hoping you will have To and Go as option. I used First char(T/G) to get ascii code and got product with first part of num.

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
  "capacities-pre": function ( a ) {
      var x = a.substring(0, a.length - 2);
      var x_unit = (a.substring(a.length-2, a.length-1)).charCodeAt(0);
      return parseInt( x * x_unit, 10 );
  },

  "capacities-asc": function ( a, b ) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },

  "capacities-desc": function ( a, b ) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
} );
αƞjiβ
  • 3,056
  • 14
  • 58
  • 95