Search code examples
jquerysortingdatatablesclickpreventdefault

How can I prevent ordering by click on column names in datatables?


I want to prevent, that by click on the column names the order changes.

I tried:

"ordering": false,

This actually removes the click possibility.But then the ordering does not work anymore. I want to keep that, only prevent the user to be able to click on the column names. I tried everything like:

$(".sorting").addClass('sorting_disabled').removeClass('sorting');

or

$(".sorting").click(function(){return false;});

or

  $( ".sorting" ).click(function( event ) {
  event.preventDefault();
});

Nothing worked.


Solution

  • You can use the following:

    $(document).ready(function() {
    
        var table = $('#example').DataTable( {
            "initComplete": function(settings, json) {
                $('th.sorting').off();
                $("th.sorting").css('cursor', 'default');
                $("th.sorting_asc").css('cursor', 'default');
                $("th.sorting_desc").css('cursor', 'default');
            }
        } );
    
        // to show sorting is still possible:
        table.order.listener( '#mysorter', 0 );
    
    } );
    

    This removes the sorting events from the table's column headers (the jQuery off() function), and ensures the mouse icon does not change to a hand when you roll over the headings.

    It leaves the arrows in place, so you can see what sort is in effect.

    To show that sorting is still possible, I added a button to the page:

    <button id="mysorter" type="button">Click Me!</button>
    

    The table.order.listener() causes column index 0 to be sorted asc/desc with each button click.

    (If you also want to get rid of the sort arrows, see here.)