jQuery Datatables - how to programatically sort by

2020-08-17 03:49发布

问题:

So I have a datatable:

$(tables[i]).DataTable({
    paging: false,
    searching: false,
    info: false,
    ordering: true,
    autoWidth: false,
    columns: [ ... column stuff here ... 
        {name: "Name"},
        {name: "Account"},
        {name: "Number"}
    ]
});

later in code, I watch for a click event on a button so that I can grab some data from the table and then sort by a column

var columnName = $('.mySelectBox').val();
var columnNumber = 0;

if(columnName === "Account")
    columnNumber = 1;

var table = $(tables[i]).DataTable();

I would like to now sort by either column 0 or column one on this button click. But not on any other column.

//this doesn't work for me
table.sort( [ [columnNumber, 'desc'] ] );

回答1:

I use .order() instead of .sort(). Example:

$('#dataTables-example').DataTable().order([0, 'desc']).draw();

where 0 is the id of the column.



回答2:

You can easily do that using order method of the table. Youcan adopt the following technique.

We need to do two things here.

  • Get current column index
  • Apply ascending or descending action on particular column on click of a icon

Here let us assume we have a button or link to which click to bind.

$(".arrow-sort-ascending").bind("click", {
 // Sorting should happen here
}

Getting column index

I use generic way to get column name. If you are using Jquery, we can fetch the column index using this.

myColumn = $(parent).prevAll().length

where parent should be the th of particular column.

Applying ascending or descending sort

 // ascending
 myTable.order([myColumn, "asc"]).draw()

So if we put the code in a single section, it looks like this.

table = myTable // This is datatable you initialized

$(".arrow-sort-ascending").bind("click", {table: table}, function(event){
    parent = $(event.target).parent()
    myIndex = $(parent).prevAll().length;
    table.order([myIndex, "asc"]).draw()
}

So whenever we click the arrow-up icon, it sorts the clicked column.