Skip to content

Instantly share code, notes, and snippets.

@zubayerahamed
Created February 10, 2018 05:15
Show Gist options
  • Save zubayerahamed/657c3b2b534fb51dd6ede03d4e489896 to your computer and use it in GitHub Desktop.
Save zubayerahamed/657c3b2b534fb51dd6ede03d4e489896 to your computer and use it in GitHub Desktop.
jQuery DataTable example (Disable sorting on specific column)
<html>
<head>
<title>Datatable</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
</head>
<body>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th data-nosort='Y'>Position</th>
<th>Office</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
</tr>
</tbody>
</table>
<br/>
<hr/>
<br/>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th data-nosort='Y'>Office</th>
<th>Age</th>
<th>Start date</th>
<th data-nosort='Y'>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function () {
$('table#example').each(function (tindex, table) {
var noSortColumns = [];
$(table).find('th').each(function (thindex, column) {
if ($(this).attr('data-nosort')) {
var value = $(this).attr('data-nosort');
if(value === 'Y'){
noSortColumns.push(thindex);
}
}
});
$(table).DataTable({
"columnDefs": [{
"targets": noSortColumns,
"orderable": false
}]
});
});
});
</script>
</body>
</html>
@zubayerahamed
Copy link
Author

You can disable sorting on specific column.
Just Enter attribute like data-nosort="Y" on column head definition in table.
You can create as many table as you need with same id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment