Alexey F Shevelyov Alexey F Shevelyov - 1 year ago 192
jQuery Question

Datatables JS - HTML5 Way To Disable Sorting On Specific Column(s)?

You know how you can use HTML5 to initialize some of the options on your table rather than using Javascript to accomplish the same. Whether one way better than the other is outside of the scope of this question.

Please See HTML 5 data attributes To Set Options To Get More Information

The goal of this question is to find an answer to how can some columns be disabled using HTML5 initialization.

The basic Javascript Initializer looks like this:

$(document).ready(function() {

} );

Then this is for instance how you would set the page length using JS withing the initialization function:

$('#example').dataTable( {
"pageLength": 50
} );

Ok getting closer - here is a JS way to do disable sorting on column 1 and 3 for instance it for instance - adding this line inside the initialization function:

$('#example').dataTable( {
"pageLength": 50,
"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 1, 3 ] }]
} );

If your table has at least for columns those 2 of them would not be sortable.

Now there is also a way for instance to set the page length, (display order...) for a table using HTML5 attribute data-, such as this:

<table data-order='[[ 1, "asc" ]]' data-page-length='25'>
<th>Start date</th>
<th data-class-name="priority">Salary</th>

My Question Is:

How to make for instance column 1 and 3 not sortable USING HTML5 DATA- ATTRIBUTE?

I have tried every option I can imagine - this is my last attempt

data-columnDefs="[{"bSortable": false, "Targets": [3]}]"

The fact that I am here indicates that I have tried all the resources I could possibly use, including Datatable JS Official Website, Google, and my indeed most favorite one StackOverflow which although has some somewhat related questions but do not help to solve this specific problem.

And as always - I appreciate every one of you my brothers and sisters for any help and effort on that questions!!! Love & Piece Be With You All My People!!!

Answer Source

You were very close. The correct data- attribute is shown below:

<table id="example" class="display" data-column-defs='[{"sortable": false, "targets": [1,3]}]'>

According to the manual:

There are two important points to consider when using data-* attributes as initialization options:

  • jQuery will automatically convert from dashed strings to the camel case notation used by DataTables (e.g. use data-page-length for pageLength).
  • If using a string inside the attribute it must be in double quotes (and therefore the attribute as a whole in single quotes). This is another requirement of jQuery's due to the processing of JSON data data.

See this jsFiddle for code and demonstration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download