Bardsworth
Bardsworth

Reputation: 408

Datatables Sort Arrow Functionality

I am using DataTables and it is working marvelously. As it works now when you click on the column header (anywhere on the header) it sorts. And toggles between ascending and descending. But the request now is to have two distinct buttons one that would sort ascending and the other that would sort descending respectively, instead of having the whole header be the active trigger.

Do I have to append to each header and add my own buttons or is there something built into datatables that i am missing.

If i do have to add my own buttons, i'd love being pointed in the right direction.

Thanks a million!

Upvotes: 1

Views: 8458

Answers (2)

davidkonrad
davidkonrad

Reputation: 85518

Unfortunately there is no builtin functionality for this in jquery dataTables. But it is very easy to implement. Here are the steps :

1) Remove the default header icons, in 1.10.x use this CSS

table.dataTable thead .sorting, 
table.dataTable thead .sorting_asc, 
table.dataTable thead .sorting_desc {
    background: none;
}

2) Remove white-space wordwrap and ugly outlines as well

th {
  white-space: nowrap;
  outline: none;
}

3) Create a class that style the buttons

.sort-btn {
   padding: 0px;
   float: right;
   font-size: 10px;
}

4) After you have initialised the dataTable, cycle through the <th>'s. For each, unbind the default click event, add .asc and .desc buttons, and inject events for ordering the column ascending or descending for each button :

$('#example th').each(function(index, th) {
  $(th).unbind('click');
  $(th).append('<button class="sort-btn btn-asc">&#9650;</button>');
  $(th).append('<button class="sort-btn btn-desc">&#9660;</button>');

  $(th).find('.btn-asc').click(function() {
     table.column(index).order('asc').draw();
  }); 
  $(th).find('.btn-desc').click(function() {
     table.column(index).order('desc').draw();      
  }); 
});    

5) The result looks like this : enter image description here

demo -> http://jsfiddle.net/wyLzgjv5/

Upvotes: 1

kabstergo
kabstergo

Reputation: 771

well if the point here is just change the default icons for sorting you can just overwrite this classes

.sorting_asc {
  background: url("my_custom_image_asc") no-repeat scroll right center transparent;
}

.sorting_desc {
  background: url("my_custom_image_desc") no-repeat scroll right center transparent;
}

Upvotes: 1

Related Questions