shinkou shinkou - 1 year ago 110
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>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<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>
var tbldata;

tbldata = $("#tbldata").DataTable();

var tbldata = $("#tbldata").DataTable();
<table id="tbldata">

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 (
at va (
at HTMLTableElement.<anonymous> (
at Function.each (
at r.each (
at r.m [as dataTable] (
at r.h.fn.DataTable (
at HTMLDocument.<anonymous> (
at j (
at k ( undefined

Answer Source

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).

  columns: [{ title: 'First Name', data: 'FirstName' }] //etc, etc...