Datatable: fixed width for selected columns only

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

So the following attribute will not work in my case (since the number of columns should be fixed in this 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.

+4
source share
1 answer

Why not let the aoColumns -array function be dynamically generated?

 // 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() }); }); 

Using this approach, the data will be initialized correctly, regardless of whether the table has 1, 3, or 1000 columns.

If you want to estimate the width of the columns based on the column heading and not their indexes, you will need to change the aoColumn function to 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; } 
+4
source

Source: https://habr.com/ru/post/1497021/


All Articles