rob
rob

Reputation: 2146

Can't set DataTables column width on a dynamically generated table

I have some jquery that posts some data, gets a list back as a JSON response and builds a datatable based on the list data. Everything works well, however I have one seemingly simple issue: I cannot get the column widths in my table declaration to to persist.

My code looks something like this:

//some magic happens and I get a result like this
json_result = ['eggs', 'bananas', 'purple']

//declare the table
var result_table = $( table_selector )
table = result_table.DataTable({
              //set two different width columns
              columnDefs: [
                     { "width": "10%", "targets": 0 },
                     { "width": "90%", "targets": 1 }
                    ]
          });

//build the table rows based on result
for (i=0, i<json_result.length, i++){
    var new_row = '<tr><td><input type="checkbox"></td><td>' +json_result[i] + '</td></tr>'
    table.row.add(new_row).draw();
   }

// table.columns.adjust().draw(); <-- tried this to no avail
table.draw();

The result is a perfectly good table that fits well in it's container...but the column widths are split 50/50. These same column defs seem to work fine on other tables in my application. I feel like I'm missing something simple!

Upvotes: 0

Views: 3910

Answers (1)

Forty3
Forty3

Reputation: 2229

From a forum thread here datatables.net, disable the "auto width" functionality via:

$(document).ready( function () {
  $('#example').dataTable( {
    "bAutoWidth": false
  } );
} );

Reference: legacy.datatables.net:

Upvotes: 2

Related Questions