Phil Phil - 1 year ago 189
Javascript Question

dataTable prevent column resizing when filtering data

I have a dataTable which I am filtering dynamically once the table has been initialized. I have a JS function that takes 1 arg which is the string to be used as the filter. I'm setting the filter on the table using...

oTable = fnFilter(strFilter);

This works fine, but after the table is filtered the columns seem to re-size themselves.
I already have bAutoWidth set to false, so I'm not sure what else I can apply that will prevent the columns from resizing. I want the sizes I have defined in the th tags to remain no matter what data is present.

Answer Source

bAutoWidth is just a flag indicating whether dataTables should calculate the widths automatically. Setting it to false is an optimisation feature, see the docs :

Enable or disable automatic column width calculation. This can be disabled as an optimisation (it takes some time to calculate the widths) if the tables widths are passed in using aoColumns.

But the browser will still expand / shrink the <td>'s according to their content. This is how tables work. To achieve what you want, the trick is to use sScrollX and aoColumns like this :

var dataTable = $('#example').dataTable({
  sScrollX: "100%",
  aoColumns: [ 
    { "sWidth": "50px" },
    { "sWidth": "50px" },
    { "sWidth": "50px" },
    { "sWidth": "50px" },
    { "sWidth": "50px" }

This gives a table with the width of 250px, each column 50px - regardless of the content. sScrollX forces dataTable to maintain the width both of the table and the columns.

See this fiddle -> demonstrating that the above apporach also is working after a call to fnFilter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download