Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - Datatables sorting - how to ignore text in column?

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
      }
      ]
  });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...