0

Sort won't work with html elements in table cell.

Tried adding the aoColumnDefs into it. Also specify column data for the column with 'sType': 'html' and the sort does not seems to work.

Attached example code here (jsfiddle)

yhtan
  • 71
  • 1
  • 2
  • 7

2 Answers2

1

I have faced this issue before on some project, use mRender() instead of fnCreatedCell(). The render function receives a type as a second argument from where you can detect if the rendering if for 'display' or 'sort' among other things. So, if type is 'display' you can return the HTML and otherwise return the raw data.

var data = [
  ["test", [20.2, "green"], "test"],
  ['test1', ['10.2', 'red'], "test"],
  ['test2', ['15.2', 'red'], "test"],
  ['test3', ['0', 'red'], "test"],
  ['test4', ['0.5', 'green'], "test"],
  ['test5', ['1.5', 'green'], "test"],
];  

$(document).ready(function()
{
    $('#data2').DataTable(
    {
      bSort: true,
      aaData: data,
      aaSorting: [[1, 'asc']],
      aoColumnDefs: [
        { 
          bSortable: true,
          sType: "numeric", 
          aTargets: [1],
          mRender: function(data, type)
          {
            if (type !== 'display')
              return data[0];

            return '<label style="color:' + data[1] + '">' + data[0] + '</label>';
          },
        }
      ]
    });    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src=https://cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.9.4/css/jquery.dataTables.css">

<table id="data2" class="">
  <thead>
  <tr>
    <th>col1</th>
    <th>col2</th>
    <th>col3</th>
  </tr>
  </thead>
</table>
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • Solved my problem! Thank you for this! Jquery Datatable is problematic when it comes to HTML-comma or HTML-decimal number format. It really helps a lot. @Shidersz – Lapiz the Programmer Dec 02 '19 at 08:02
0

I was struggling with numbers followed by HTML, and no matter what options I chose the HTML change the numbers from being sorted numerically to alphabetically.

I finally came across the following (for my DataTables 1.11) which saved my bacon. I was able to output just the ID number that I wanted it to sort by into data-order, and that solved everything:

<td data-order="{id}"><{id} <span>{DESC}</span></td>