Skip to content Skip to sidebar Skip to footer

Specify Column Data Type With A Attribute For Datatables

We're using the DataTables jQuery plugin (http://www.datatables.net) to create sortable tables. This plugin auto-detects the data type of the data in each column. When you want to

Solution 1:

Here is an absolutely cool way to do it:

Your header HTML:

<tableid="sorted-table"><thead><tr><thdata-s-type="string">Number</th><thdata-s-type="html">Complex Name</th><th>Price</th><thdata-b-sortable="false">Action</th></tr></thead>
...

Your JS:

$('#sorted-table').dataTable({
   ...
   "aoColumns": $('#sorted-table').find('thead tr th').map(function(){return $(this).data()})
});

Note: those dashes in data attributes are needed. They get converted to camelCase form by jQuery which makes it compatible with the data tables API.

Solution 2:

Picking up on CBroe's comment, this is exactly what I do. Just ensure that your custom attributes are prefixed with data-, such as data-stype='currency' per the HTML specs.

Solution 3:

Having your JS loop through and check for attributes on the headers would work, but you can't just invent an sType attribute and have it show up in the DOM. You'd have to subvert a valid but unused attribute like headers (and that might cause trouble for screen readers; there may be a better option).

Edit:

OK, having read CBroe's comment, I guess it is possible to give an element an arbitrary attribute.

So, if you wanted to be HTML5 compliant, you could name the property data-sType and then do something like this:

var aoColumns = [];

$('#accountTable > th').each(function() {
   var sType = $(this).getAttribute("data-sType");
   aoColumns.push(sType ? sType : null);
});

$('#accountTable').dataTable({
   ...
   "aoColumns": aoColumns
});

Solution 4:

Thanks to all for your help! I had to make a couple tweaks to Russell Zahniser's comment for it to work for me:

  1. Changed $('#accountTable > th') to $('#accountTable thead th')
  2. Changed aoColumns.push(sType ? sType : null) to aoColumns.push(sType ? { "sType" : "currency" } : null)

End result:

var aoColumns = [];

$('#accountTable thead th').each(function() {
   var sType = $(this).getAttribute("data-sType");
   aoColumns.push(sType ? { "sType" : "currency" } : null);
});

$('#accountTable').dataTable({
   ...
   "aoColumns": aoColumns
});

Post a Comment for "Specify Column Data Type With A Attribute For Datatables"