Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable sorting only for one column in JQUERY Datatable

Im trying to enable sorting based on one column only in a datatable. but its not working. This is the way I tried

var myTable = $("#tbl_main").dataTable({
    "dom": "<'tableinfobar'i><'tablesearchbox'f><'tablestarfilter'><'tablebody't>S<'tablelength'l><'tablepaging'p>",
    "ordering": false,
    "columnDefs": [{"targets": [0, 6],"searchable": false}, {"targets":2, "type":"html-num","orderable":true}],
    "lengthMenu": [
        [10, 20, 50, 100, 500, -1],
        [10, 20, 50, 100, 500, "All"]
    ]
}).show();

Here I need to enable sorting only for second column only and tried that in columnDefs

like image 507
Sandeep Thomas Avatar asked Mar 09 '16 04:03

Sandeep Thomas


2 Answers

add class no-sort to all the <th> except the column which you want to sort.. kindly check https://jsfiddle.net/24zztcL9/

I have enabled sort only for 2nd column "Position"

HTML

<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th class="no-sort">Name</th>
                <th>Position</th>
                <th class="no-sort">Office</th>
                <th class="no-sort">Age</th>
                <th class="no-sort">Start date</th>
                <th class="no-sort">Salary</th>
            </tr>
        </thead>
     </table>

jQuery

$(document).ready(function() {
  $('#example').DataTable({

    "ordering": true,
    columnDefs: [{
      orderable: false,
      targets: "no-sort"
    }]

  });
});
like image 156
RRR Avatar answered Oct 08 '22 14:10

RRR


Rather than using columnDefs I prefer using columns like this:

$(document).ready(function() {
    $('#example').DataTable({
        "columns":[
            {
                "sortable": false
            },
            {
                "sortable": true
            },
            {
                "sortable": false
            },
            {
                "sortable": false
            },
            {
                "sortable": false
            },
            {
                "sortable": false
            }
        ]
    });
});

Working JSFiddle

Either approach works, I just prefer the granular control of the columns array.

like image 35
annoyingmouse Avatar answered Oct 08 '22 14:10

annoyingmouse