Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sorting on values in a data-sort attribute with Jquery Datatables

I have to do some custom sorts with Jquery Datatables. I do not want to write custom sort functions for every custom sort.

I want to define a value to sort on and have Datatables ignore the original column values, if value is defined.

For example:

<td data-sort="111123">E 1.111,23</td>

I want Jquery Datatables to sort this column numerically on 111123.

<td data-sort="19801220">20-12-1980</td>

I want Jquery Datatables to sort this column numerically on 19801220.

<td>a string</td>

I want Jquery Datatables to sort this column by its original value a string.

http://www.datatables.net/plug-ins/sorting has "Hidden title numeric sorting" which is close to what I want, but requires me to specify for every datatable on which column this custom sorting applies. I have too many datatables of differing sizes to do this in a reasonable time. I just want to make Datatables always sort this hidden value / data-* attribute if it is present. No need for custom sort definitions on specific columns.

Related: jQuery DataTables: how to sort by custom parameter value rather than the content of the cell? but unfortunately no answer as to how to sort simply by custom parameter, instead pointers to custom sorting scripts.

like image 996
Pake Beet Avatar asked Nov 29 '13 12:11

Pake Beet


2 Answers

You can use data-order attr, for example

<table class="table table-bordered table-hover">
<thead>
    <tr>
        <th>Date</th>
        <th>Count</th>
    </tr>
</thead>
<tbody>
<?php
   $count = 0;
   foreach($users as $user) {?>
      <tr>
         <td data-order="<?php echo $count ?>">
            <?php echo $user['createdDate']; ?>
         </td>
         <td>
            <?php echo $user['count']; ?>
         </td>
         </tr>
   <?php
      $count++;
   }?>
   <tr>
      <td data-order="999999999999999999999999999"> <!--always last-->
          Total
      </td>
      <td>
         <?php echo count($users); ?>
      </td>
  </tr>

more information HTML5 data-* attributes

like image 79
Vitall Avatar answered Oct 09 '22 01:10

Vitall


I found an easy solution that works for me and does not require too much code or changes to datatables.js.

It is very similar to the requirements of the question, but not exactly the same.

Instead of data-sort you can use a HTML comment tag.

<td data-sort="111123">E 1.111,23</td>

becomes

<td><!-- 000000111123 -->E 1.111,23</td>

By zero-padding an int they will be sorted as a string. The zero-padding makes the sort behave as you'd expect: sorting the integers from high to low.

Solution works for dates, ints and strings. For dates and ints you can use a scripting language to output them in the way you want (eg: zero-padded, formatted as yyyy-mm-dd).

like image 31
Pake Beet Avatar answered Oct 09 '22 02:10

Pake Beet