yhtan
yhtan

Reputation: 71

Jquery Datatable sort not working with html elements

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)

Upvotes: 0

Views: 1686

Answers (2)

DriveItLikeYouStoleIt
DriveItLikeYouStoleIt

Reputation: 669

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>

Upvotes: 0

Shidersz
Shidersz

Reputation: 17190

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>

Upvotes: 1

Related Questions