4

I have a table, for which the number of columns are not fixed. However, the first 3 columns are always present.

So, the following attribute would not work in my case(as the number of columns needs to be fixed in that approach)

"aoColumns": [
        {"sWidth": "50px"},
        {"sWidth": "100px"},
        {"sWidth": "100px"},
        null,
        null,
        null
    ]
 } );

I tried something like:

"aoColumns": [[1, { "sWidth": "50px" }] ]

This also does not work, as it creates some errors.

Please suggest a good way.

ipradhansk
  • 352
  • 1
  • 10
  • 36

1 Answers1

4

Why not let a function dynamically generate the aoColumns-array?

// function that generates the aoColumns-array based on the tables <thead>
// columns beyond #3 get a fixed 25px width (just to be illustrative)
// expand the switch if certain columns need certain fixed widths
function aoColumns() {
    var ao = [];
    $("#table th").each(function(i) {
        switch (i) {
            case 0 : 
                ao.push({"sWidth": "50px"});
                break;
            case 1 : 
                ao.push({"sWidth": "100px"});
                break;
            case 2 : 
                ao.push({"sWidth": "100px"});
                break;
            default :
                ao.push({"sWidth": "25px"});
                break;
        }
    });
    return ao;
}

$(document).ready(function () {
    var table = $('#table').dataTable({
        aoColumns: aoColumns()
    });
});

By using this approach, datatables will initialize correct no matter if the table has 1, 3 or 1000 columns.

If you want to evaluate the column widths based on each columns caption rather than their indexes, you'll need to change the aoColumn-function a litte bit :

function aoColumns() {
    var ao = [];
    $("#table th").each(function(i, th) {
        var caption=$(th).text();
        switch (caption) {
            case 'A' : 
                ao.push({"sWidth": "50px"});
                break;
            case 'B' : 
                ao.push({"sWidth": "100px"});
                break;

            /*...
            and so on
            ...*/

            default :
                ao.push({"sWidth": "25px"});
                break;
        }
    });
    return ao;
}
davidkonrad
  • 83,997
  • 17
  • 205
  • 265