Custom sort function not called onLoad of Jquery datatable

Custom sort function not called onLoad of Jquery datatable

biswa1shawbiswa1shaw Posts: 4Questions: 2Answers: 0

I have added a custom sort functionality in datatable. It works fine when the table header is clicked. However, On pageLoad I want the table to be sorted by that column using the same logic as provided in the custom sort function. It does not seem to do so. Here is my code snippet

$(document).ready(function(){
  $("#stripedTableAcp").DataTable({
    "columnDefs": [
      { 
        "type": "acp_name",
        "targets": 3
      } 
    ],
    "order": [[ 3, "asc" ]],
    "pageLength": 100,
    "lengthMenu": [100, 500, 1000, 2000, 5000]
  });

  $.fn.dataTableExt.oSort["acp_name-desc"] = function (x, y)
  {
    console.log("1");
    x = jQuery(x).text();
    y = jQuery(y).text();

    temp = x.split("-");
    xPart1 = temp[0];
    xPart2 = parseInt(temp[1]);

    temp = y.split("-");
    yPart1 = temp[0];
    yPart2 = parseInt(temp[1]);

    if(xPart1 > yPart1)
    {
      return -1;
    }

    if(xPart2 > yPart2)
    {
      return -1;
    }

    return 1;
  };

  $.fn.dataTableExt.oSort["acp_name-asc"] = function (x, y)
  {
    console.log("2");
    x = jQuery(x).text();
    y = jQuery(y).text();

    temp = x.split("-");
    xPart1 = temp[0];
    xPart2 = parseInt(temp[1]);

    temp = y.split("-");
    yPart1 = temp[0];
    yPart2 = parseInt(temp[1]);

    if(xPart1 > yPart1)
    {
      return 1;
    }

    if(xPart2 > yPart2)
    {
      return 1;
    }

    return -1;
  }
});

Please note that the console.log added to the function is fired when the table header is clicked but not upon page load

datatable version is 1.10.19 as provided by the CDN

Any help is greatly appreciated.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 5,532Questions: 19Answers: 1,232
    Answer ✓

    I haven't messed with ordering plugins much but my guess is you need to initialize the plugins before initializing Datatables. Try moving your Dataatable init code after the plugins.

    Kevin

  • biswa1shawbiswa1shaw Posts: 4Questions: 2Answers: 0

    I cannot thank you enough. I don't know how this simple idea eluded me for a better part of the evening. Perhaps I was too blinded by js hoisting.
    You saved from more hours of unavoidable agony. Thanks again Kevin

    Biswajit

Sign In or Register to comment.