Detect number of columns, or fail gracefully when an invalid column is specified

Detect number of columns, or fail gracefully when an invalid column is specified

YoavShapiraYoavShapira Posts: 1Questions: 0Answers: 0
edited March 2012 in General
Some of my tables have dynamic columns, and the following initialization code causes a popup failure message from datatables. Can I detect the number of columns in a data table programmatically, or can I tell datatables to just swallow that error in the column definitions?

Sample initialization code:
jQuery(function($) {
$('#mytable').dataTable({
bPaginate: true, // turn on paging
bSort: true, // turn on sorting
iDisplayLength: 100, // # of rows per page

aaSorting: [[1, "desc"]], // Start with 2nd column sorted

aoColumnDefs: [
{ "bSortable" : false, "aTargets": [ 0 ] },
{ "bSortable" : true, "aTargets" : [ 1, 2, 3, 4, 5 ] },
{ "asSorting" : ["desc", "asc"], "aTargets" : [ 1, 2, 3, 4 ] },
{ "sType" : "numeric", "aTargets" : [ 2, 3 ] }
]
});
});

If I have a table with 5 columns, i.e. 1 less than 6, I get an error like so:

DataTables warning: Requested unknown parameter '5' from the data source for row 0.

This is using DataTables 1.8.2, jQuery 1.6.2, all browsers.

Help detecting the number of columns, or otherwise improving the above code, would be appreciated.

Alternatively, can I somehow tell Datatables to swallow / ignore this problem?

Thanks in advance!

Replies

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin
    > can I somehow tell Datatables to swallow / ignore this problem?

    Currently no - if you've defined 6 columns, then its going to use 6 columns. The closest to swallowing the error would be to set sDefaultContent to be an empty string for column 6, resulting in an empty cell.

    > Can I detect the number of columns in a data table programmatically,

    Perhaps just something like this:

    [code]
    ${'#example_table thead th').length
    [/code]

    is all you need - and you can modify the columns object based on that information.

    Allan
This discussion has been closed.