code, data

DataTables with Dynamic Columns

I was exploring the DataTables library for jQuery and was a bit shocked that it did not support dynamic columns for a fixed-width array of json objects natively. You would think that the top search result for jquery table library could support json data directly as the view but datatables only supports hard-coding the columns found in the table. That got super annoying once I added a column… I’d have to update my data scripts to create the column, make sure the backend served it, and then add it to the javascript.

Example of datatables on jsfiddle

I couldn’t find much of an example of using datatables for the features I needed but I liked the built-in search, sort, and show n-entries function. I figured others might have this problem so I’ve patched together an example from a few different sources and compiled it in this jsfiddle The code should be pretty self-explanatory but I’ll highlight a few things below.

To dynamically create a datatable it’s easiest to use jquery to create table html and then load that into datatables init method. This has the added benefit of allowing you to change to another jquery library besides datatables easily and also makes it easy to create a dynamic datatable by using the destroy function.

The script expects data of the format {order: [c1,c2,c3],data[{c1: c1_val,c2…}]}. However you could modify the script pretty easily to infer the column names from the first row of data. I used order because order was important for my application

Also demonstrated is how to hide columns by name instead of an arbitraty idx and to use hidden columns to create complex fields like the link from player name to rotoworld

Please comment with any questions and I’ll try to get back to you as soon as I can

Leave a Reply

Your email address will not be published.