Skip to content

Instantly share code, notes, and snippets.

@JakubNei
Forked from krusynth/dataTables_patch.js
Created April 27, 2017 08:48
Show Gist options
  • Save JakubNei/6c022b5b797aad5095cd90831d6671ca to your computer and use it in GitHub Desktop.
Save JakubNei/6c022b5b797aad5095cd90831d6671ca to your computer and use it in GitHub Desktop.
dataTables.js requires you to have "good" tables. If your table has an uneven number of columns per row, and you're getting the dreaded " Cannot read property 'mData' of undefined " this will fix it.
// dataTables.js is great! But it requires you to have "good" tables in
// the first place. If your table has an uneven number of columns per
// row, and you're getting the dreaded "Cannot read property
// 'mData' of undefined" this'll fix it. If you're missing a thead or
// tbody you'll get that error too - this won't fix that!
$(document).ready(function() {
// We need to make sure every row in our table has the same number of columns.
// Otherwise dataTable doesn't work.
$('table').each(function(i, elm) {
elm = $(elm);
// Get the longest row length.
var maxsize = 0;
var trs = elm.find('tr');
trs.each(function(i, tr) {
if($(tr).find('td,th').length > maxsize) {
maxsize = $(tr).find('td,th').length;
}
});
// Repeat the loop, this time padding out our rows
trs.each(function(i, tr) {
var tr = $(tr);
var missing = maxsize - tr.find('td,th').length;
if(missing > 0) {
var extra_elms = '<td></td>';
if(tr.parent().prop('tagName').toLowerCase() === 'thead') {
extra_elms = '<th></th>';
}
for(i=0; i<missing; i++) {
tr.append(extra_elms);
}
}
});
});
//
// Put your actual call to dataTable here!!!!
// $('table').dataTable({
// 'scrollY': '400px',
// 'scrollX': true,
// 'scrollCollapse': true,
// 'paging': false,
// 'ordering': false,
// 'info': false
// });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment