Problem with the jQuery DataTables order listener
Problem with the jQuery DataTables order listener
I am using the DataTable jQuery plugin and I would like to disable the default ordering of each column when you click on the TH element and instead specify another element for ordering (which will be a child of each TH).
I have this in JS
var table = $('.table-striped').DataTable({
"ordering": false
});
table.order.listener( $('#sort'), 1);
And this in HTML
<table class="table table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th><span id="sort">Col 1</span></th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td><span>2</span></td>
<td><span>CHARLIE</span></td>
<td><span>DELTA</span></td>
</tr>
<tr>
<td><span>1</span></td>
<td><span>ALPHA</span></td>
<td><span>BETA</span></td>
</tr>
</tbody>
So I believe that when clicking on the SPAN with ID of 'sort', the table should be sorted by column 1- however it does not :( Any ideas??
BTW, jQuery & DataTables are all initalised correctly and I can get other DataTable functionality like pagination working :)
Here is the Fiddle: http://jsfiddle.net/isherwood/d20djg91/
This question has an accepted answers - jump to answer
Answers
BTW, this is a copy from StackOverflow
So, my solution was to enable the default order on DataTables, and then to prevent the ordering event having an affect on elements [that I didnt want the sort event to work on] in the TH with a return false:
Hope that helps!
The way you have found is basically the "correct" way (or you could unbind the event handlers, which would be my preferred method). Using
ordering
disables ordering completely, which is why this extra set is needed -ordering
must be left enabled.Allan
Allan- how would I unbind the event handlers in this case?
Use
$('th').off('click');
.http://live.datatables.net/rupupeyo/1/edit
Allan
Allan- thanks for that. However, I dont believe it works! Have a look at the JS Bin, I have updated it using your logic to disable sorting on a DIV I have placed in the TH, however sorting still works on that element.
Any ideas?
I see. My example did work as it removed the sort listener (try and click on the header elements - nothing happens).
What you want is something different, likely involving a call to
stopPropagation()
. Can you update the example I can above to show what you are actually looking for please.Allan
Thanks Allan- stopPropagation does work thanks but then return false achieves the same thing as well: http://live.datatables.net/rupupeyo/5/edit
Yup -
return false;
will do it as well. But worth being aware of what it is doing.Allan