13

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'] ] );
6
  • Try fnSort instead of sort? Or add order: [[columnNumber, 'desc' ]] to $(tables[i]).DataTable({ ... }); ? Commented Jul 16, 2015 at 16:07
  • aaSorting: [[ columnNumber, "desc" ]] or if you want to use fnsort do your dataTable initialization in a variable and fnsort on that variable Commented Jul 16, 2015 at 16:12
  • @CyberneticTwerkGuruOrc When I try fnSort it tells me it's not a function. Commented Jul 16, 2015 at 16:14
  • do you do it like this? myTable.fnSort( [ [columnNumber,'desc'] ] ); Commented Jul 16, 2015 at 16:15
  • Yes, in exactly that manner. Commented Jul 16, 2015 at 16:15

2 Answers 2

26

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

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

where 0 is the id of the column.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.