shinkou shinkou - 2 months ago 32
jQuery Question

Weird jQuery DataTables Initialization Behaviour

I have the following code. And I wonder why it works in one way but not the other.

<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Chart</title>
<link href="./css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="./js/jquery-3.1.0.min.js"></script>
<script src="./js/jquery.dataTables.min.js"></script>
<script>
/*
// THIS BLOCK DOES NOT WORK
var tbldata;

$(document).ready
(
function()
{
tbldata = $("#tbldata").DataTable();
}
);
*/

// THIS SINGLE LINE WORKS
var tbldata = $("#tbldata").DataTable();
</script>
</head>
<body>
<div>
<table id="tbldata">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>


It gives me the following error if I uncomment the block which I marked as not working and comment out the single line which works.

jQuery.Deferred exception: Cannot read property 'aDataSort' of undefined TypeError: Cannot read property 'aDataSort' of undefined
at V (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:65:443)
at va (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:70:61)
at HTMLTableElement.<anonymous> (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:91:148)
at Function.each (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:2815)
at r.each (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:1003)
at r.m [as dataTable] (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:82:388)
at r.h.fn.DataTable (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:166:245)
at HTMLDocument.<anonymous> (http://192.168.33.10:5000/static/test.html:30:45)
at j (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:29568)
at k (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:29882) undefined

Answer

When calling the DataTables initializer without any options, it expects a populated thead so it can try to detect columns and their attributes.

Add at least one <th> element to your thead, and then the commented code will work.

The uncommented line isn't really working. At the point the javascript runs, the element does not yet exist on the page! So the selector grabs 0 elements and the initializer is not really running, thus, no error.

Alternatively (and my preferred method of initializing DTs for the most part)... give your initializer an array of column definition(s).

$('#mytable').DataTable({
  columns: [{ title: 'First Name', data: 'FirstName' }] //etc, etc...
})