Cannot read property 'mData' of undefined - Datatables [duplicate] - javascript

I have an issue with Datatables. I also went through this link which didn't yield any results. I have included all the prerequisites where I'm parsing data directly into the DOM.
Script
$(document).ready(function() {
$('.viewCentricPage .teamCentric').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bPaginate": false,
"bFilter": true,
"bSort": true,
"aaSorting": [
[1, "asc"]
],
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0]
}, {
"bSortable": true,
"aTargets": [1]
}, {
"bSortable": false,
"aTargets": [2]
}],
});
});

FYI dataTables requires a well formed table. It must contain <thead> and <tbody> tags, otherwise it throws this error. Also check to make sure all your rows including header row have the same number of columns.
The following will throw error (no <thead> and <tbody> tags)
<table id="sample-table">
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
<tr>
<td>data-1</td>
<td>data-2</td>
</tr>
</table>
The following will also throw an error (unequal number of columns)
<table id="sample-table">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>
For more info read more here

A common cause for Cannot read property 'fnSetData' of undefined is the mismatched number of columns, like in this erroneous code:
<thead> <!-- thead required -->
<tr> <!-- tr required -->
<th>Rep</th> <!-- td instead of th will also work -->
<th>Titel</th>
<!-- th missing here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td>
<td>Titel</td>
<td>Missing corresponding th</td>
</tr>
</tbody>
While the following code with one <th> per <td> (number of columns must match) works:
<thead>
<tr>
<th>Rep</th> <!-- 1st column -->
<th>Titel</th> <!-- 2nd column -->
<th>Added th</th> <!-- 3rd column; th added here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td> <!-- 1st column -->
<td>Titel</td> <!-- 2nd column -->
<td>th now present</td> <!-- 3rd column -->
</tr>
</tbody>
The error also appears when using a well-formed thead with a colspan but without a second row.
For a table with 7 colums, the following does not work and we see "Cannot read property 'mData' of undefined" in the javascript console:
<thead>
<tr>
<th>Rep</th>
<th>Titel</th>
<th colspan="5">Download</th>
</tr>
</thead>
While this works:
<thead>
<tr>
<th rowspan="2">Rep</th>
<th rowspan="2">Titel</th>
<th colspan="5">Download</th>
</tr>
<tr>
<th>pdf</th>
<th>nwc</th>
<th>nwctxt</th>
<th>mid</th>
<th>xml</th>
</tr>
</thead>

Having <thead> and <tbody> with the same numbers of <th> and <td> solved my problem.

I had this same problem using DOM data in a Rails view created via the scaffold generator. By default the view omits <th> elements for the last three columns (which contain links to show, hide, and destroy records). I found that if I added in titles for those columns in a <th> element within the <thead> that it fixed the problem.
I can't say if this is the same problem you're having since I can't see your html. If it is not the same problem, you can use the chrome debugger to figure out which column it is erroring out on by clicking on the error in the console (which will take you to the code it is failing on), then adding a conditional breakpoint (at col==undefined). When it stops you can check the variable i to see which column it is currently on which can help you figure out what is different about that column from the others. Hope that helps!

This can also occur if you have table arguments for things like 'aoColumns':[..] which don't match the correct number of columns. Problems like this can commonly occur when copy pasting code from other pages to quick start your datatables integration.
Example:
This won't work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 1, 'desc' ]],
'aoColumns': [
null,
null,
null,
null,
null,
null,
{
'bSortable': false
}
]
});
</script>
But this will work:
<table id="dtable">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<td>data 1</td>
<td>data 2</td>
</tbody>
</table>
<script>
var dTable = $('#dtable');
dTable.DataTable({
'order': [[ 0, 'desc' ]],
'aoColumns': [
null,
{
'bSortable': false
}
]
});
</script>

One more reason why this happens is because of the columns parameter in the DataTable initialization.
The number of columns has to match with headers
"columns" : [ {
"width" : "30%"
}, {
"width" : "15%"
}, {
"width" : "15%"
}, {
"width" : "30%"
} ]
I had 7 columns
<th>Full Name</th>
<th>Phone Number</th>
<th>Vehicle</th>
<th>Home Location</th>
<th>Tags</th>
<th>Current Location</th>
<th>Serving Route</th>

Tips 1:
Refer to this Link you get some Ideas:
https://datatables.net/forums/discussion/20273/uncaught-typeerror-cannot-read-property-mdata-of-undefined
Tips 2:
Check following is correct:
Please check the Jquery Vesion
Please check the versiion of yours CDN or your local datatable related .min & css files
your table have <thead></thead> & <tbody></tbody> tags
Your table Header Columns Length same like Body Columns Length
Your Using some cloumns in style='display:none' as same propery apply in you both Header & body.
your table columns no empty, use something like [ Null, --, NA, Nil ]
Your table is well one with out <td>, <tr> issue

You have to remove your colspan and the number of th and td needs to match.

I faced the same error, when tried to add colspan to last th
<table>
<thead>
<tr>
<th> </th> <!-- column 1 -->
<th colspan="2"> </th> <!-- column 2&3 -->
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
and solved it by adding hidden column to the end of tr
<thead>
<tr>
<th> </th> <!-- column 1 -->
<th colspan="2"> </th> <!-- column 2&3 -->
<!-- hidden column 4 for proper DataTable applying -->
<th style="display: none"></th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<!-- hidden column 4 for proper DataTable applying -->
<td style="display: none"></td>
</tr>
</tbody>
Explanaition to that is that for some reason DataTable can't be applied to table with colspan in the last th, but can be applied, if colspan used in any middle th.
This solution is a bit hacky, but simpler and shorter than any other solution I found.
I hope that will help someone.

in my case this error occured if i use table without header
<thead>
<tr>
<th>example</th>
</tr>
</thead>

I am getting a similar error. The problem is that the header line is not correct. When I did the following header line, the problem I was having was resolved.
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th colspan="6">Common Title</th>
</tr>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>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>
</tbody>
</table>

Slightly different problem for me from the answers given above. For me, the HTML markup was fine, but one of my columns in the javascript was missing and didn't match the html.
i.e.
<table id="companies-index-table" class="table table-responsive-sm table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Created at</th>
<th>Updated at</th>
<th>Count</th>
</tr>
</thead>
<tbody>
#foreach($companies as $company)
<tr>
<td>{{ $company->id }}</td>
<td>{{ $company->name }}</td>
<td>{{ $company->created_at }}</td>
<td>{{ $company->updated_at }}</td>
<td>{{ $company->count }}</td>
</tr>
#endforeach
</tbody>
</table>
My Script:-
<script>
$(document).ready(function() {
$('#companies-index-table').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: "{{ route('admincompanies.datatables') }}",
columns: [
{ name: 'id' },
{ name: 'name' },
{ name: 'created_at' },
{ name: 'updated_at' }, <-- I was missing this line so my columns didn't match the thead section.
{ name: 'count', orderable: false },
],
});
});
</script>

I had a dynamically generated, but badly formed table with a typo. I copied a <td> tag inside another <td> by mistake. My column count matched. I had <thead> and <tbody> tags. Everything matched, except for this little mistake I didn't notice for a while, because my column had a lot of link and image tags in it.

This one drove me crazy - how to render a DataTable successfully in a .NET MVC view. This worked:
**#model List<Student>
#{
ViewData["Title"] = "Index";
}
<h2>NEW VIEW Index</h2>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
#foreach (var element in Model)
{
<tr>
<td>#Html.DisplayFor(m => element.ID)</td>
<td>#Html.DisplayFor(m => element.FirstName)</td>
<td>#Html.DisplayFor(m => element.LastName)</td>
</tr>
}
</tbody>
</table>**
Script in JS file:
**$(document).ready(function () {
$('#example').DataTable();
});**

For those working in Webforms using GridView:
Moses's answer is totally correct. But since we're generating the table, the thead tag isn't generated by default. So to solve the problem add [YourGridViewID].HeaderRow.TableSection = TableRowSection.TableHeader to your backend, below of the DataBind() method call (if you're using it). This configuration takes the HeaderText value of the Field in your GridView as the value of the th tag it generates inside the thead.

In my case, and using ASP.NET GridView, UpdatePanel and with DropDownList (with Chosen plugin where I reset value to zero using a Javascript line), I got this error and tried everything with no hope for days. The problem was that the code of my dropdown in code behind was as follows and when I select a value twice to apply its action to selected grid rows I get that error. I thought for days it's a Javascript issue (again, in my case) and finally the fix was giving zero for the drowpdown value with the update process:
private void ddlTasks_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ddlTasks.SelectedValue != 0) {
ChangeStatus(ddlTasks.SelectedValue);
ddlTasks.SelectedValue = "0"; //// **This fixed my issue**
}
dvItemsGrid.DataSource = CreateDatasource();
dvItemsGrid.DataBind();
dvItemsGrid.UseAccessibleHeader = true;
dvItemsGrid.HeaderRow.TableSection = TableRowSection.TableHeader;
}
This was my fault:
$('#<%= DropDownList.ClientID%>').val('0').trigger("chosen:updated").chosen();

I had encountered the same issue but I was generating table Dynamically. In my case, my table had missing <thead> and <tbody> tags.
here is my code snippet if it helped somebody
//table string
var strDiv = '<table id="tbl" class="striped center responsive-table">';
//add headers
var strTable = ' <thead><tr id="tableHeader"><th>Customer Name</th><th>Customer Designation</th><th>Customer Email</th><th>Customer Organization</th><th>Customer Department</th><th>Customer ContactNo</th><th>Customer Mobile</th><th>Cluster Name</th><th>Product Name</th><th> Installed Version</th><th>Requirements</th><th>Challenges</th><th>Future Expansion</th><th>Comments</th></tr> </thead> <tbody>';
//add data
$.each(data, function (key, GetCustomerFeedbackBE) {
strTable = strTable + '<tr><td>' + GetCustomerFeedbackBE.StrCustName + '</td><td>' + GetCustomerFeedbackBE.StrCustDesignation + '</td><td>' + GetCustomerFeedbackBE.StrCustEmail + '</td><td>' + GetCustomerFeedbackBE.StrCustOrganization + '</td><td>' + GetCustomerFeedbackBE.StrCustDepartment + '</td><td>' + GetCustomerFeedbackBE.StrCustContactNo + '</td><td>' + GetCustomerFeedbackBE.StrCustMobile + '</td><td>' + GetCustomerFeedbackBE.StrClusterName + '</td><td>' + GetCustomerFeedbackBE.StrProductName + '</td><td>' + GetCustomerFeedbackBE.StrInstalledVersion + '</td><td>' + GetCustomerFeedbackBE.StrRequirements + '</td><td>' + GetCustomerFeedbackBE.StrChallenges + '</td><td>' + GetCustomerFeedbackBE.StrFutureExpansion + '</td><td>' + GetCustomerFeedbackBE.StrComments + '</td></tr>';
});
//add end of tbody
strTable = strTable + '</tbody></table>';
//insert table into a div
$('#divCFB_D').html(strDiv);
$('#tbl').html(strTable);
//finally add export buttons
$('#tbl').DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});

In addition to inconsistent and numbers, a missing item inside datatable scripts columns part can cause this too. Correcting that fixed my datatables search bar.
I'm talking about this part;
"columns": [
null,
.
.
.
null
],
I struggled with this error till I was pointed that this part had one less "null" than my total thead count.

in my case the cause of this error is i have 2 tables that have same id name with different table structure, because of my habit of copy-paste table code. please make sure you have different id for each table.
<table id="tabel_data">
<thead>
<tr>
<th>heading 1</th>
<th>heading 2</th>
<th>heading 3</th>
<th>heading 4</th>
<th>heading 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
<td>data-4</td>
<td>data-5</td>
</tr>
</tbody>
</table>
<table id="tabel_data">
<thead>
<tr>
<th>heading 1</th>
<th>heading 2</th>
<th>heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>data-1</td>
<td>data-2</td>
<td>data-3</td>
</tr>
</tbody>
</table>

You need to wrap your your rows in <thead> for the column headers and <tbody> for the rows. Also ensure that you have matching no. of column headers <th> as you do for the td

I may be arising by aoColumns field. As stated HERE
aoColumns: If specified, then the length of this array must be equal
to the number of columns in the original HTML table. Use 'null' where
you wish to use only the default values and automatically detected
options.
Then you have to add fields as in table Columns
...
aoColumnDefs: [
null,
null,
null,
{ "bSortable": false },
null,
],
...

I found some "solution".
This code doesn't work:
<table>
<thead>
<tr>
<th colspan="3">Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
But this is ok:
<table>
<thead>
<tr>
<th colspan="2">Test</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
I think, that the problem is, that the last TH can't have attribute colspan.

Related

Appending a table row from body tag to another table after updating elements within the row

I was told it is good practice to never use HTML tags in JavaScript. So I'm trying my very best to execute the following, but I'm not getting what I want.
I have 2 tables:
Table #1: a table I use to append rows to.
Table #2: a hidden table that has only 1 row, I use that row to change its content and append it to Table #1
Table #1
<table id="myTable">
<thead>
<tr>
<th>Full Name</th>
<th>ID</th>
<th>Email</th>
<th>Phone Number</th>
<th>Job Title</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Table #2
<table id='hiddenTable'>
<tbody>
<tr>
<td><span id="fname"></span></td>
<td><span id="id"></span></td>
<td><span id="email"></span></td>
<td><span id="pnumber"></span></td>
<td><span id="job"></span></td>
</tr>
</tbody>
</table>
Append Function
function addRow(data){
$('#fname').text(data.fname);
$('#id').text(data.id);
$('#email').text(data.email);
$('#pnumber').text(data.pnumber);
$('#job').text(data.job);
var row = $('#hiddenTable').children('tbody').children('tr:first').clone();
$('#myTable > tbody:last-child').append(row);
}
All the snaps are updated everytime addRow() is executed, but when retrieving the row element from the hidden table, it remains empty, unchanged.
please explain why is this happening? and help me make this work without using html tags in javascript and without using the insert row function.
As suggested by #CBroe; the main issue is duplicate ids getting assigned to DOM element. To overcome that first change hidden table's HTML a bit to have class instead of id. Please have a look at below snippet:
function addRow(data) {
//first clone the row from hidden table
var row = $('#hiddenTable').children('tbody').children('tr:first').clone();
//find the span having unique class assigned to them and then set the value
row.find('.fname').text(data.fname);
row.find('.id').text(data.id);
row.find('.email').text(data.email);
row.find('.pnumber').text(data.pnumber);
row.find('.job').text(data.job);
//append the newly formed row to main table
$('#myTable tbody').append(row);
}
$(function() {
var data1 = {
fname: "some name",
id: "some id",
email: "some#email.com",
pnumber: "1212121212",
job: "some job"
};
addRow(data1);
var data2 = {
fname: "some name 22",
id: "some id 22",
email: "some22#email.com",
pnumber: "88888888888888",
job: "some job 22"
};
addRow(data2);
});
#hiddenTable {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>Full Name</th>
<th>ID</th>
<th>Email</th>
<th>Phone Number</th>
<th>Job Title</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table id='hiddenTable'>
<tbody>
<tr>
<td><span class="fname">aaaaaa</span>
</td>
<td><span class="id"></span>
</td>
<td><span class="email"></span>
</td>
<td><span class="pnumber"></span>
</td>
<td><span class="job"></span>
</td>
</tr>
</tbody>
</table>
All you have done is correct and should work as you expected unless your data object's incorrect. Make a console of your data object and try to figure out how you can extract property from that.
function addRow(data) {
$('#fname').text(data.fname);
$('#id').text(data.id);
$('#email').text(data.email);
$('#pnumber').text(data.pnumber);
$('#job').text(data.job);
var row = $('#hiddenTable tr').first().clone();
$('#myTable tbody').append(row);
}
var data = {
fname: 'first name',
id: '12121',
email: 'email#gmail.com',
pnumber: '111111111',
job: 'my job'
}
addRow(data);
#hiddenTable {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>Full Name</th>
<th>ID</th>
<th>Email</th>
<th>Phone Number</th>
<th>Job Title</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table id='hiddenTable'>
<tbody>
<tr>
<td><span id="fname"></span>
</td>
<td><span id="id"></span>
</td>
<td><span id="email"></span>
</td>
<td><span id="pnumber"></span>
</td>
<td><span id="job"></span>
</td>
</tr>
</tbody>
</table>
Try this JSFiddle solution.
I change something on addRow function:
function addRow(data){
$('#hiddenTable #fname').text(data.fname);
$('#hiddenTable #id').text(data.id);
$('#hiddenTable #email').text(data.email);
$('#hiddenTable #pnumber').text(data.pnumber);
$('#hiddenTable #job').text(data.job);
var row = $('#hiddenTable tbody').html();
$('#myTable > tbody').append(row);
}

How to reference a data attribute of another element?

I am trying to create a responsive table, that collapses from a horizontal to a vertical layout. For that I use a :before pseudo-element, that gets its value from a data attribute. Consider the following dom-structure:
td:before {
content: attr(data-th);
}
<table>
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
<th>Fourth</th>
</tr>
</thead>
<tbody>
<tr>
<td data-th="First">Alpha</td>
<td data-th="Second">Beta</td>
<td data-th="Third">Gamma</td>
<td data-th="Fourth">AnotherGreekLetter</td>
</tr>
</tbody>
</table>
This works fine and well, until you realize, that you have to write every single data-attribute by hand, since every new row of data requires the data-attribute.
Ideally I would like to have something like this:
td:before:nth-of-type(4n+1) {
content: attr(data-th:nth-of-type(4n+1));
}
td:before:nth-of-type(4n+2) {
content: attr(data-th:nth-of-type(4n+2));
}
<table>
<thead>
<tr>
<th data-th="First">First</th>
<th data-th="Second">Second</th>
<th data-th="Third">Third</th>
<th data-th="Fourth">Fourth</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alpha</td>
<td>Beta</td>
<td>Gamma</td>
<td>AnotherGreekLetter</td>
</tr>
</tbody>
</table>
where I am referencing the data-attribute of the th-nodes.
Now, as far as I know, there is no way of walking the dom-tree with just css, so I assume this would only be possible with javascript. Yet, I have never made use of the data-attribute, so I am hoping that I am wrong about that.
Can I make this work with (in descending order of preference): only css, php, javascript?
Don't think you can do this via CSS, you could probably use a slightly different approach if using jQuery too as you could use an ID to locate the values from the header and write it out to the body e.g.
<table>
<thead>
<tr data-id="1">
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr data-id="1"></tr>
</tbody>
</table>
And the jQuery:
$(document).ready(function() {
$("thead tr th").each(function( index ) {
$("tbody tr[data-id='" + $(this).parent().attr('data-id') + "']").append('<td>' + $(this).text() + '</td>');
});
});
http://codepen.io/anon/pen/kXdkyY
Hopefully this gives you an alternative idea of how you could loop through and grab data in a different way.

How to add search to some individual columns of DataTable in the footer?

I need to add filtering of different types (textbox, dropdown) to some(!) individual columns in DataTable to the footer. That is, I want to be able to search by a single column for each filter I add to the footer and the type of the filter will depend on a column, say, for the column 0 it's a textbox, for the column 1 it's a dropdown, for the column 5 it's a datepicker.
Here's a test example. Note the new type of the constructor (DataTable, not dataTable).
$("#my-table").DataTable({
//.....
, 'initComplete': function (settings, json) {
var cl = this.api().columns(1); //2nd column
$(cl.footer()).html("fdsfds"); //doesn't work
//this.api().columns().every(function(){
//var column = this;
//$(column.footer()).html('fdsfsdfd'); //doesn't work either
//});
//neither this
//var api = this.api();
// $(api.column(1).footer()).html('dsfs2222');
});
What's the matter?
You need to do two things here.
Add a tfoot to your table so it will have a space to add it
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="4" style="text-align:right">Total:</th>
<th></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>$320,800</td>
</tr>
</tbody>
</table>
Use footerCallBack like specified here http://datatables.net/examples/advanced_init/footer_callback.html You also used columns instead of column.
$(document).ready(function() {
$('#example').DataTable({
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
$(api.column(1).footer()).html("test text");
}
});
});

Sorting jQuery dataTables by class name when there is no type or value

I'm using DataTables: https://www.datatables.net/
Heres my HTML:
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover center" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>title 1</td>
<td><span class="on"></span></td>
</tr>
<tr>
<td>2</td>
<td>title 2</td>
<td><span class="off"></span></td>
</tr>
<tr>
<td>3</td>
<td>title 3</td>
<td><span class="on"></span></td>
</tr>
</tbody>
I want to sort that table with last column but there's no value to sort... just class "on" and "off". Is there any atrribute that I can add to link tag like rel or something to put there 0/1 values? Or should I do that with JavaScript?
Here's JS code:
$('#dataTables-example').DataTable({
responsive: true,
"order": []
});
Take a look at dataTables columns / columnDefs render() function. You can return various content or values depending on the purpose : filter, display, type or sort. If you want to sort the column by 0 / 1 based on the <span> has the classes .on or .off, you can do this :
var table = $('#dataTables-example').DataTable({
columnDefs : [
{
targets: [2],
render: function ( data, type, full, meta ) {
if (type == 'sort') {
return $(data).find('span').hasClass('on') ? 1 : 0;
} else {
return data;
}
}
}
]
});
demo -> http://jsfiddle.net/9zvyhgb5/

delete all datatables using jQuery

so, I am using datatables along with jQuery, and am a bit stumped as to why this is not working. My HTML looks like this:
<table id="surnamePrimaryPartitionTable" border=1 class="display partitionDisplay">
<caption>Partitions</caption>
<thead>
<tr style="background-color: #afeeee;">
<th>Partition</th>
<th>CPU %</th>
<th>Search Count</th>
<th>Person Count</th>
<th>Disk Space</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I have several tables, each of which follows a similar format, and each of which uses the partitionDisplay class (really just a class that I use so that I can select all the tables later using jQuery).
So, the problem arises when I try to destroy the datatables. Here is what I have:
function DeletePartitionInformation(data) {
jQuery(".partitionDisplay").each(function(){
jQuery(this).dataTable().fnDestroy();
});
jQuery("table tbody").each(function() {
jQuery(this).html("");
})
}
This code seems to work correctly for the first table, but throws an exception and doesn't work on any subsequent tables. The javascript error message I am getting is the following:
Uncaught TypeError: Cannot read property 'asSorting' of undefined
A quick Google search on this error says that it generally arises from having elements nested in a tag. This does not appear to be the problem, however. I will post the code for the other three tables to demonstrate this:
<table id="surnamePrimarySubpartitionTable" border=1 class="display partitionDisplay">
<caption>SubPartitions</caption>
<thead>
<tr style="background-color: #afeeee;">
<th>Partition</th>
<th>SubPartition</th>
<th>CPU %</th>
<th>Search Count</th>
<th>Person Count</th>
<th>Disk Space</th>
<th>Begin</th>
<th>End</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table id="givenNullSurnamePartitionTable" border=1 class="display partitionDisplay">
<caption>Partitions</caption>
<thead>
<tr style="background-color: #98fb98;">
<th>Partition</th>
<th>CPU %</th>
<th>Search Count</th>
<th>Person Count</th>
<th>Disk Space</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table id="givenNullSurnameSubpartitionTable" border=1 class="display partitionDisplay">
<caption>SubPartitions</caption>
<thead>
<tr style="background-color: #98fb98;">
<th>Partition</th>
<th>SubPartition</th>
<th>CPU %</th>
<th>Search Count</th>
<th>Person Count</th>
<th>Disk Space</th>
<th>Begin</th>
<th>End</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
One final note: I am actually able to get the behavior I want if I use the below code. Obviously I would prefer not to, however, since I'd really like to loop over the elements rather than hard-code the element id's in.
function DeletePartitionInformation(data) {
jQuery("#surnamePrimarySubpartitionTable").dataTable().fnDestroy();
jQuery("#surnamePrimaryPartitionTable").dataTable().fnDestroy();
jQuery("#givenNullSurnameSubpartitionTable").dataTable().fnDestroy();
jQuery("#givenNullSurnamePartitionTable").dataTable().fnDestroy();
jQuery("table tbody").each(function() {
jQuery(this).html("");
})
}
Uncaught TypeError: Cannot read property 'asSorting' of undefined
This seems to suggest it may be trying to destroy dataTables that weren't created.
The static fnTables should give you an Array of only the <table> elements with a dataTable:
var tables = $.fn.dataTable.fnTables(true);
$(tables).each(function () {
$(this).dataTable().fnDestroy();
});

Categories

Resources