1

First, I can disable the sorting in the table headers by just

$("button.disable-sorting").click(function(){
    $("table thead th").off("click.DT");
});

now my problem is how to bind back the sorting on the table headers, I tried

$("button.restore-sorting").click(function(){
    $("table thead th").bind("click.DT");
});

but seem's not working. Any help ideas on how to bind back the sorting capabilities of the datatables table headers?

PS: im on DataTables 1.10.12

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164
  • Possible duplicate of [disable a column sorting using jquery datatables](http://stackoverflow.com/questions/3932587/disable-a-column-sorting-using-jquery-datatables) –  Jul 11 '16 at 06:19
  • @theinarasu: nope, his issue is on datatables initialize while mine is after initialize/on click event. – Juliver Galleto Jul 11 '16 at 06:24
  • @CodeDemon, please try adding the event handler in the bind statement. – Krishnakumar_Muraleedharan Jul 11 '16 at 06:31
  • @Krishnakumar_Muraleedharan: Sorry I don't get it, can you explain a bit? which event handler? and bind statement? – Juliver Galleto Jul 11 '16 at 06:33
  • @CodeDemon, my understanding is that the bind event will have the syntax $(selector).bind(eventType,eventHandlerFunction). Can you please try following the same syntax when you are trying to bind the event again? – Krishnakumar_Muraleedharan Jul 11 '16 at 06:43
  • @Krishnakumar_Muraleedharan: please read more about jquery bind and unbind events. its clear what I'm trying to do, I want to bind back the event named "click.DT" to the table headers!! – Juliver Galleto Jul 11 '16 at 08:22

1 Answers1

2

I would store original event listeners right after initilization. In the example below I preserve all events for the very first <th> by saving them to an array map events :

var table = $('#example').DataTable({
  initComplete: function() {
    $.each($._data($('#example thead th')[0], 'events'), function(name, obj) {
      events[name] = obj[0]
    })
  }
})  

Now you have a map of the "native" dataTables events on the form

events['click'] => old event handler
events['keypress'] => old event handler
...

And then it is really simple to turn sorting (and other dataTables event-driven features) on and off for a particular header (or all headers). Here is a small demo with disable / enable buttons :

//remove original event listeners, add alternative 
$("#disable").click(function() {
 $("#example thead th:nth-child(1)")
   .unbind()
   .bind('click', function() { 
      alert('all listeners removed')
   })
})  
//restore any original event 
$("#enable").click(function() {
  var $th = $("#example thead th:nth-child(1)")
  $th.unbind()
  for (var name in events) {
    $th.bind(name, events[name])
  }
})  

demo -> http://jsfiddle.net/8sbcage4/ (disables / enables dataTables events for the first header)

davidkonrad
  • 83,997
  • 17
  • 205
  • 265