Adding the sum of a field in Datatables - javascript

This question has been asked before but as an absolute beginner with JavaScript I don't know how to apply this to my code. I would like the sum for both the 'G' field and sum for the 'AB' field to be displayed in the footer of my table.
Here's my code
<div align="center">
<table id = 'battingtbl' class="display compact nowrap">
<thead>
<tr>
<th>YEAR</th>
<th>AGE</th>
<th>G</th>
<th>AB</th>
</tr>
</thead>
<tbody>
{% for stat in playerdata.masterbatting_set.all %}
<tr>
<td>{{ stat.year }}</td>
<td>{{ stat.age }}</td>
<td>{{ stat.g }}</td>
<td>{{ stat.ab }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function () {
$('#battingtbl').DataTable({
"searching": true,
"pageLength": 40,
"scrollX": true,
"paging": false,
"info": false,
})
});
</script>

I normally do not suggest to populate DataTable with HTML source, I find this way tedious and slow.
However, assuming you want those totals to get recalculated upon each re-draw (table filtering), I'd suggest to employ drawCallback option to populate your totals:
drawCallback: () => {
// grab DataTables insurance into the variable
const table = $('#battingtbl').DataTable();
// extract all the data for all visible columns
const tableData = table.rows({search:'applied'}).data().toArray();
// summarize row data for columns 3,4 (indexes 2, 3)
const totals = tableData.reduce((total, rowData) => {
total[0] += parseFloat(rowData[2]);
total[1] += parseFloat(rowData[3]);
return total;
// starting point for reduce() totals for 2 columns equal to zero each
}, [0,0]);
// populate footer cells for columns 3, 4 (indexes 2, 3) with corresponding array total
$(table.column(2).footer()).text(totals[0]);
$(table.column(3).footer()).text(totals[1]);
}
Above requires you to append <tfoot> section to the static HTML part you prepare server-side:
<tfoot>
<tr>
<th colspan="2">Totals:</th>
<th></th>
<th></th>
</tr>
</tfoot>
So, complete example might look something, like this:
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<div align="center">
<table id = 'battingtbl' class="display compact nowrap">
<thead>
<tr>
<th>YEAR</th>
<th>AGE</th>
<th>G</th>
<th>AB</th>
</tr>
</thead>
<tbody>
<tr>
<td>2016</td>
<td>24</td>
<td>15</td>
<td>6</td>
</tr>
<tr>
<td>2018</td>
<td>32</td>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>2016</td>
<td>28</td>
<td>14</td>
<td>9</td>
</tr>
<tr>
<td>2015</td>
<td>25</td>
<td>9</td>
<td>7</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2">Totals:</th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
$('#battingtbl').DataTable({
"searching": true,
"pageLength": 40,
"scrollX": true,
"paging": false,
"info": false,
drawCallback: () => {
const table = $('#battingtbl').DataTable();
const tableData = table.rows({
search: 'applied'
}).data().toArray();
const totals = tableData.reduce((total, rowData) => {
total[0] += parseFloat(rowData[2]);
total[1] += parseFloat(rowData[3]);
return total;
}, [0, 0]);
$(table.column(2).footer()).text(totals[0]);
$(table.column(3).footer()).text(totals[1]);
}
})
});
</script>
</body>
</html>

Related

How to add strikethrough to dropdown select box on jquery datatable and filter out on the basis of it

I have jquery Datatable as follows, and there is also a strikethrough text and I want to make it filterable, but upto now its not even being showing with strikethrough on the dropdown. My jquery datatable is as follows:
$(document).ready(function() {
var table = $("#example").DataTable({
"order": [ 1, "asc" ],
// "lengthMenu": [[ 100, 200, 500,-1], [ 100, 200, 500,'All']],
"pageLength": -1,
"lengthChange": false,
"bFilter": "false",
"searchable": false,
orderCellsTop: true,
"bPaginate": false,
"bInfo": false
});
$('.filterRow th').each( function (i) {
var title = $(this).text();
var select = $('<select><option value="">All</option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var term = $(this).val();
table.column( i ).search(term, false, false ).draw();
} );
let includedArr = [];
let colData = table.column( i ).data().unique().sort().each( function ( d, j ) {
if(d != ""){
select.append( '<option value="'+d+'">'+d+'</option>' );
}
});
} );
} );
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<table id="example" class="display" style="width:100%">
<tbody>
<tr>
<td>N</td>
<td>101</td>
<td>1</td>
<td>01</td>
<td>10</td>
<td>20</td>
</tr>
<tr>
<td>N</td>
<td>102</td>
<td>1</td>
<td>02</td>
<td>(20)</td>
<td>20</td>
</tr>
<tr>
<td>N</td>
<td>103</td>
<td>1</td>
<td>03</td>
<td>
<del>10</del>
</td>
<td>20</td>
</tr>
</tbody>
<thead>
<tr>
<th rowspan="2">Bldg</th>
<th rowspan="2">Unit</th>
<th rowspan="2">Floor</th>
<th rowspan="2">Stack</th>
<th colspan="2">
Floor Level
</th>
</tr>
<tr>
<th>Floor 1</th>
<th>Floor 2</th>
</tr>
<tr class="filterRow">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
Here you can see on floor1 column with strikethrough text, but it is not showing on the dropdown value.
I have even tried to adding inline classes as:
if (d.indexOf("del") >= 0){
select.append( '<option style="text-decoration: line-through;" value="'+d+'">'+d+'</option>' );
}else{
select.append( '<option value="'+d+'">'+d+'</option>' );
}
But, this to does not seems to working. How could I add strikethrough text on select box, and make it filterable.
I am not sure if you can do that with select option. Maybe do it using jQuery and bootstrap instead by using ul and li -
$(document).ready(function() {
var table = $("#example").DataTable({
"order": [1, "asc"],
// "lengthMenu": [[ 100, 200, 500,-1], [ 100, 200, 500,'All']],
"pageLength": -1,
"lengthChange": false,
"bFilter": "false",
"searchable": false,
orderCellsTop: true,
"bPaginate": false,
"bInfo": false
});
$('.filterRow th').each(function(i) {
var title = $(this).text();
var select = $('<div class="dropdown" id="select' + i + '"><a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#"><span class="selectedvalue">All</span><span class="caret"></span><ul class="dropdown-menu"><li data-value="">All</li></ul></div>')
.appendTo($(this).empty());
let includedArr = [];
let colData = table.column(i).data().unique().sort().each(function(d, j) {
if (d != "") {
var cell = table.column(i).nodes().toArray().find(f => f.innerHTML.trim() == d);
var searchValue = $(cell).attr("data-search");
select.find('ul').append('<li data-value="' + searchValue + '">' + d + '</li>');
}
});
select.find('.dropdown-menu a').click(function(e) {
var term = $(this).closest("li").attr("data-value");
var text = $(this).html();
$(this).closest(".dropdown").find(".selectedvalue").html(text);
if (term == "") {
table.column(i).search('').draw();
return;
}
table.column(i).search("^" + escapeRegExp(term) + "$", true, false, true).draw();
});
});
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
});
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<table id="example" class="display" style="width:100%">
<tbody>
<tr>
<td data-search="N">N</td>
<td data-search="101">101</td>
<td data-search="1">1</td>
<td data-search="01">01</td>
<td data-search="10">10</td>
<td data-search="20">20</td>
</tr>
<tr>
<td data-search="N">N</td>
<td data-search="102">102</td>
<td data-search="1">1</td>
<td data-search="02">02</td>
<td data-search="(20)">(20)</td>
<td data-search="20">20</td>
</tr>
<tr>
<td data-search="N">N</td>
<td data-search="103">103</td>
<td data-search="1">1</td>
<td data-search="03">03</td>
<td data-search="-10-">
<del>10</del>
</td>
<td data-search="20">20</td>
</tr>
</tbody>
<thead>
<tr>
<th rowspan="2">Bldg</th>
<th rowspan="2">Unit</th>
<th rowspan="2">Floor</th>
<th rowspan="2">Stack</th>
<th colspan="2">
Floor Level
</th>
</tr>
<tr>
<th>Floor 1</th>
<th>Floor 2</th>
</tr>
<tr class="filterRow">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
Note: I have not styled the dropdowns.

Jquery Datatable drag and drop with row grouping

I have used jquery dataTable and I have a requirement as below:
If I drag the row (- BRAND NAME:....) then it should drag between rows only and with all it's content.
If I drag content of the row group then it should not overlap with other group.
Here is what I have done so far:
HTML:
<table id="example">
<thead>
<tr>
<th>Name</th>
<th>type</th>
<th>age</th>
</tr>
</thead>
<tbody id="sortable">
<tr id="1">
<td>Name</td>
<td>Type1</td>
<td>Age</td>
</tr>
<tr id="2">
<td>Name</td>
<td>Type1</td>
<td>Age</td>
</tr>
<tr id="3">
<td>Name</td>
<td>Type2</td>
<td>Age</td>
</tr>
<tr id="4">
<td>Name</td>
<td>Type2</td>
<td>Age</td>
</tr>
</tbody>
</table>
Jquery:
var table = $('#example').DataTable({
"searching": false,
"paging": false,
"info": false,
"order": [[0, "asc"]],
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="groups"><td class="tdgroups" colspan="22" style="Cursor:hand !important;BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + '- BRAND NAME: ' + group + '</td></tr>'
);
last = group;
}
});
}
});
$("#sortable").sortable();
$("#sortable").disableSelection();
Link of Jsfiddle: DEMO
You can change your markup a little bit. Place each row group in separate <tbody>
and make those sortable.
var table = $('#example').DataTable({
"searching": false,
"bSort": false,
"paging": false,
"info": false,
});
$("#example>tbody").sortable({
items: "tr:not(.group-row)"
});
$("#example").sortable({
items: "tbody"
}).disableSelection();
table.dataTable tbody tr.group-row {
cursor: move;
background-color: rgb(237, 208, 0);
font-weight: 700;
color: #006232;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.0/css/jquery.dataTables.css">
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<table id="example">
<thead>
<tr>
<th>Name</th>
<th>type</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr class="group-row">
<td>- BRAND NAME: Type 1</td>
<td></td>
<td></td>
</tr>
<tr id="1">
<td>NameA</td>
<td>Type1</td>
<td>Age</td>
</tr>
<tr id="2">
<td>NameB</td>
<td>Type1</td>
<td>Age</td>
</tr>
</tbody>
<tbody>
<tr class="group-row">
<td>- BRAND NAME: Type 2</td>
<td></td>
<td></td>
</tr>
<tr id="3">
<td>NameD</td>
<td>Type2</td>
<td>Age</td>
</tr>
<tr id="4">
<td>NameC</td>
<td>Type2</td>
<td>Age</td>
</tr>
</tbody>
</table>
Inspired by the answer by Munim Munna, I created a version that automatically modifies the table-structure by utilizing only javascript/jquery.
let table = $('#example').DataTable({
"searching": false,
"sort": false,
"order": [[1, "asc"], [0, "asc"]],
"paging": false,
"info": false,
drawCallback: function (settings) {
let api = this.api();
let rows = api.rows({ page: 'current' }).nodes();
if ($(rows).parent().is("tbody")) {
$(rows).unwrap();
}
let last = null;
let group_index = -1;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
// make previous group sortable
if (last) {
$("#example > tbody[data-group='" + group_index + "']").sortable({
items: "tr.group-row",
containment: "#example > tbody[data-group='" + group_index + "']",
opacity: 0.75
});
}
group_index++;
// add group-header before new group
$(rows).eq(i).before(
'<tbody data-group="' + group_index + '"><tr class="group-header"><td colspan="3">' + '- BRAND NAME: ' + group + '</td></tr></tbody>'
);
last = group;
}
// modify row and append to tbody
$(rows).eq(i).attr('data-group', group_index).addClass('group-row').appendTo("tbody[data-group='" + group_index + "']");
});
// make last group also sortable
$("#example > tbody[data-group='" + group_index + "']").sortable({
items: "tr.group-row",
containment: "#example > tbody[data-group='" + group_index + "']",
opacity: 0.75
});
// make the tbody-elements sortable and disable selection in table
$("#example").sortable({
items: "tbody",
placeholder: "tbody-placeholder",
forcePlaceholderSize: true,
opacity: 0.75
})
.disableSelection();
}
});
table.dataTable tbody tr.group-header {
cursor: move;
background-color: rgb(237, 208, 0);
font-weight: 700;
color: #006232;
}
table.dataTable .tbody-placeholder {
display: table-row;
height: 50px;
}
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="http://cdn.datatables.net/1.10.0/css/jquery.dataTables.css">
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.js"></script>
<table id="example">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td>Name1</td>
<td>Type1</td>
<td>13</td>
</tr>
<tr id="2">
<td>Name2</td>
<td>Type1</td>
<td>42</td>
</tr>
<tr id="3">
<td>Name3</td>
<td>Type2</td>
<td>33</td>
</tr>
<tr id="4">
<td>Name4</td>
<td>Type2</td>
<td>17</td>
</tr>
</tbody>
</table>

jQuery DataTables: Set a search filter for a named column upon initialization

Basically, I want to achieve this command upon initialization of my dataTables.
$('#trainings-table').DataTable().column('status:name').search('planned').draw();
So, what I've tried:
$('#trainings-table').DataTable({
columnDefs: [{
targets: 'status:name',
search: 'planned'
},
]
})
But this didn't work. I also tried changing the target to the exact column number (e.g. targets: 2) and not using this named target, but that didn't seem to be the problem.
My DataTable:
<table id="trainings-table">
<thead>
<tr>
<th data-name="name">description</th>
<th data-name="status">Status</th>
<th data-name="date">date</th>
<th date-name="duration">days</th>
</tr>
</thead>
<tbody>
<!-- Expected behaviour: This row below should be hidden after initialization -->
<tr>
<td>Training 1</td>
<td>Completed</td>
<td>28.04.2019</td>
<td>1 day</td>
</tr>
<!-- Expected behaviour: Only show row below after initialization -->
<tr>
<td>Training 2</td>
<td>Planned</td>
<td>05.05.2019</td>
<td>2 days</td>
</tr>
...
</tbody>
</table>
You need to set name property with columns or columnDefs option.
Here is the code example:
$(document).ready(function () {
var table = $('#trainings-table').DataTable({
dom: 't',
columns: [
{name: 'name'},
{name: 'status'},
{name: 'date'},
{name: 'duration'}
],
searchCols: [
null,
{search: 'Planned'},
null,
null
]
});
});
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="trainings-table">
<thead>
<tr>
<th data-name="name">description</th>
<th data-name="status">Status</th>
<th data-name="date">date</th>
<th date-name="duration">days</th>
</tr>
</thead>
<tbody>
<!-- Expected behaviour: This row below should be hidden after initialization -->
<tr>
<td>Training 1</td>
<td>Completed</td>
<td>28.04.2019</td>
<td>1 day</td>
</tr>
<!-- Expected behaviour: Only show row below after initialization -->
<tr>
<td>Training 2</td>
<td>Planned</td>
<td>05.05.2019</td>
<td>2 days</td>
</tr>
</tbody>
</table>

Inner text using javascript / jquery

I have a datatable and I want to extract the column 1
var usernames = dataTableTeamMembers.columns(1).data();
But it gives me an array like this:
Array(2)
0
:
"admin"
1
:
"catalao"
I only want the text, not the html.
How do I extract the innertext of that a tag?
There's two approaches:
With .column() (with each one):
$(document).ready(function() {
var dataTableTeamMembers = $('#example').DataTable();
dataTableTeamMembers.column(1).data().each(function(username, index){
console.log(username);
});
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger</td>
</tr>
<tr>
<td>2</td>
<td>Garrett</td>
</tr>
<tr>
<td>3</td>
<td>Tiger</td>
</tr>
<tr>
<td>4</td>
<td>Ashton</td>
</tr>
<tr>
<td>5</td>
<td>Garrett</td>
</tr>
</tbody>
</table>
And .columns() (returns array):
$(document).ready(function() {
var dataTableTeamMembers = $('#example').DataTable();
console.log(dataTableTeamMembers.columns(1).data()[0]);
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger</td>
</tr>
<tr>
<td>2</td>
<td>Garrett</td>
</tr>
<tr>
<td>3</td>
<td>Tiger</td>
</tr>
<tr>
<td>4</td>
<td>Ashton</td>
</tr>
<tr>
<td>5</td>
<td>Garrett</td>
</tr>
</tbody>
</table>
You have 3 options, depending on what you need
1 using DataTables API
var table = $('#your_table_id').DataTable().data();
for(var i = 0; i < table.length; i++)
{
var tbl_obj = table[i];
//do stuff
console.log(JSON.stringify(table[i]))
}
2 Using jquery to get all row html
$('#your_table_id tr').each(function() {
console.log($(this).html());
});
3 to get a specific cell on a row, by cell class
$('#your_table_id tr').each(function() {
var obj = $(this).find(".cell_class").html();
});
Use the one which fits more to your needs.

jQuery DataTable Order Table Based On Checkbox

I have a table:
<table id="Equipment-Table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center">
#Html.DisplayNameFor(model => model.TypeOfEquipment)
</th>
<th class="text-center">
#Html.DisplayNameFor(model => model.Deleted)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="text-center">
<td>
#Html.DisplayFor(modelItem => item.TypeOfEquipment)
</td>
<td>
#Html.DisplayFor(modelItem => item.Deleted)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</tbody>
</table>
I am using jQuery DataTables to style it and give it functionality.
This produces this:
My goal:
Order by the Deleted column. I want deleted items to be at the bottom of the list.
Here is what I have so far:
$(document).ready(function() {
var equipmentTable = $("#Equipment-Table").DataTable({
"order": [1, "asc"],
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1, 2] },
{ "bSearchable": false, "aTargets": [1, 2] }
]
});
});
How can I make this happen?
Update
<tr class="text-center">
<td>
#Html.DisplayFor(modelItem => item.TypeOfEquipment)
</td>
#if (item.Deleted)
{
<td data-order="1">
#Html.DisplayFor(modelItem => item.Deleted)
</td>
}
else
{
<td data-order="0">
#Html.DisplayFor(modelItem => item.Deleted)
</td>
}
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
$(document).ready(function() {
var equipmentTable = $("#Equipment-Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1, 2] },
{ "bSearchable": false, "aTargets": [1, 2] }
]
});
$('#Equipment-Table input[type="checkbox"]').on('change', function () {
// Update data-sort on closest <td>
$(this).closest('td').attr('data-order', this.checked ? 1 : 0);
// Store row reference so we can reset its data
var $tr = $(this).closest('tr');
// Force resorting
equipmentTable
.row($tr)
.invalidate()
.order([1, 'asc'])
.draw();
});
});
You are using the legacy DataTables API: you should avoid using that, because it is being replaced by a more verbose and readable one.
You can sort your checkbox column programatically by using a combination of the following strategy:
When the page is first rendered, set the data-sort / data-order attribute to reflect the (un)checked status. In the example below, I settled for 0 for unchecked and 1 for checked. This should be handled by your templating/layout logic.
<!-- Rendered markup for UNCHECKED -->
<td data-order="0"><input type="checkbox" /></td>
<!-- Rendered markup for CHECKED -->
<td data-order="1"><input type="checkbox" checked /></td>
We bind a click event handler to the checkbox input. When the onChange event is fired, we simply:
Dynamically update the data-sort/data-order attribute based on the checked status of the checkbox
Invalidate the cached data stored for the row (so DataTables will have to reindex the data-sort/data-order attribute), using .row().invalidate()
Resort the table using .sort()
Trigger redrawing using .draw(), as the step above does not reflow/redraw the table
Here is a proof-of-concept example:
$(document).ready(function() {
var equipmentTable = $("#Equipment-Table").DataTable({
"order": [1, "asc"]
});
// Listen to change event from checkbox to trigger re-sorting
$('#Equipment-Table input[type="checkbox"]').on('change', function() {
// Update data-sort on closest <td>
$(this).closest('td').attr('data-order', this.checked ? 1 : 0);
// Store row reference so we can reset its data
var $tr = $(this).closest('tr');
// Force resorting
equipmentTable
.row($tr)
.invalidate()
.order([ 1, 'asc' ])
.draw();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="Equipment-Table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center">
Type of Eqiupment
</th>
<th class="text-center">
Deleted
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>Lorem</td>
<td data-order="0"><input type="checkbox" /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Ipsum</td>
<td data-order="0"><input type="checkbox" /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Dolor</td>
<td data-order="1"><input type="checkbox" checked /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Sit</td>
<td data-order="1"><input type="checkbox" checked /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Amet</td>
<td data-order="0"><input type="checkbox" /></td>
<td>...</td>
</tr>
</tbody>
</table>
Update
It seems like OP is only interested in enforcing initial sorting of the table, while disabling user-initiated sorting and search. The checkboxes are also disabled by default, which means we do not need to bind event listeners to them since we do not expect the user to toggle this option. This can be done with the following config:
{
"order": [1, "asc"],
"columnDefs": [
{ "orderable": false, "targets": [0,1,2] },
],
"searching": false
}
Proof-of-concept:
$(document).ready(function() {
var equipmentTable = $("#Equipment-Table").DataTable({
"order": [1, "asc"],
"columnDefs": [{
"orderable": false,
"targets": [0, 1, 2]
}],
"searching": false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="Equipment-Table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center">
Type of Eqiupment
</th>
<th class="text-center">
Deleted
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>Lorem</td>
<td data-order="0"><input type="checkbox" disabled /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Ipsum</td>
<td data-order="0"><input type="checkbox" disabled /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Dolor</td>
<td data-order="1"><input type="checkbox" checked disabled /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Sit</td>
<td data-order="1"><input type="checkbox" checked disabled /></td>
<td>...</td>
</tr>
<tr class="text-center">
<td>Amet</td>
<td data-order="0"><input type="checkbox" disabled /></td>
<td>...</td>
</tr>
</tbody>
</table>

Categories

Resources