Datatables sorting - how to ignore text in column?

穿精又带淫゛_ 提交于 2021-02-02 09:56:14

问题


I have used this script to sort my datatable and ignore text that I do not want to sort, I'll explain.

this is the column example:

10,836
↑(10.71%)
14,836
↑(13.71%)

I want to ignore this: ↑(10.71%) and to sort according to this: 10,836.

thats my script:

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "justNum-pre": a => parseFloat(a.replace(/\D/g, "")),
  "justNum-asc": (a, b) => a - b,
  "justNum-desc": (a, b) => b - a
});
$(document).ready(function () {
  var table = $('#dataTable').DataTable({
      order: [[ 1, "desc" ]],
      scrollY: 200,
      scrollX: false,
      responsive: true,
      paging: false,
      //colReorder: true,
      //pageLength: 100,
      columns: [
          {
              "render": function(data, type, row){
                  return data.split(" ").join("<br/>");
              }
          },
          null,
          null,
          null,
          null,
          null,
          null
      ],
      columnDefs: [
      { className: "all", "targets": [ 0, 1, 3, 6 ] },
      {
        type: 'justNum',
        targets: 1
      }
      ]
  });
});

回答1:


You can do this using the DataTables orderData feature.

For example, assume your formatted data is in the first column:

10,836
↑(10.71%)

Add a second column containing only the numeric portion (no text) 10836 and define it as a hidden column.

Then, create a columnDefs section in your datatable definition - something like this:

$('#demo').DataTable( {
    "columnDefs": [
      { "orderData": [ 1 ], "targets": 0 },
      { "visible": false, "targets": 1 }
    ]
  } );

} );

This says that the first column (target index 0) will use the data in the second column (target index 1) for sorting. And the second column will be a hidden column.



来源:https://stackoverflow.com/questions/60918299/datatables-sorting-how-to-ignore-text-in-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!