Dynamically identify column

Dynamically identify column

NoBullManNoBullMan Posts: 23Questions: 6Answers: 0

Link to test case: Intranet app
Debugger code (debug.datatables.net):
Error messages shown: N/A
Description of problem:
It appears there is currently no way to create table columns at run time, just before binding ajax returned data to datatable. So, I had to initially include all possible columns to the table. I am trying to show some columns based on data in an array (of column names) and make others not visible.

These are a set of outcome labels and user can select all or a subset of these to get a count of each selected outcome.

Assuming table columns (i.e. all possible outcomes) are DB, F1, F2, F3 H1, H2, H3 and my array (selOutcomes) contains [BD, F2, H2], how can I form the following statements

var column = table.column( '**BD**:name' );

in this loop?

$.each(selOutcomes, function (index, item) {
    var column = table.column('??:name');

Or any other solution that allows me to show/hide column based on contents of an array.


  • kthorngrenkthorngren Posts: 17,294Questions: 25Answers: 4,109

    Sounds like you are using 'column.name to name the columns. Looks also like you want to use the column-selector of {string}:name to choose the column in your loop. It seems like you loop should like something like this:

    $.each(selOutcomes, function (index, item) {
        var column = table.column( item + ':name' );

    This is assuming you have the column.name defined like this (plus any other column definitions):

        columns: [
            { name: 'BD' },
            { name: 'F1' },
            { name: 'F2' },

    Not sure if this example will help but it uses jQuery ajax() to fetch the table data and defines the columns before initializing Datatables:


  • NoBullManNoBullMan Posts: 23Questions: 6Answers: 0

    Thank you Kevin.
    I saw a post similar to what you provided a few minutes after posting my question.
    I can work with this. Thank you.

  • NoBullManNoBullMan Posts: 23Questions: 6Answers: 0

    Just in case someone looks at this post later:
    I noticed after initial data table display where ALL outcome codes were displayed; when I selected a subset of outcome codes and recreated/re-initialized datatable, old column headers were still intact even though data table was only showing the selected columns data.

    I had to add these two statements before recreating datatable:

    $("#OutcomeCodesTable tbody").empty();
    $("#OutcomeCodesTable thead").empty();


    tblOutcomeCodes = $("#OutcomeCodesTable").DataTable({...});
  • kthorngrenkthorngren Posts: 17,294Questions: 25Answers: 4,109

    Good, glad its working. FYI the destroy() docs use .empty() in one the examples for the same reason :smile:


Sign In or Register to comment.