jQuery DataTables: control table width

JqueryDatatablesJquery Datatables

Jquery Problem Overview


I have a problem controlling the width of a table using the jQuery DataTables plugin. The table is supposed to be 100% of the container width, but ends up being an arbitrary width, rather less than the container width.

Suggestions appreciated

The table declaration looks like this

<table id="querytableDatasets" class="display" cellspacing="0"
cellpadding="3"     width="100%">

And the javascript

jQuery('#tab-datasets').load('/cgi-bin/qryDatasets', '', function (){  
    jQuery('#querytableDatasets').dataTable({  
        "bPaginate": false,  
        "bInfo": false,  
        "bFilter": false  
    });  
});  `  

Inspecting the HTML in Firebug, you see this (note the added style="width: 0px;")

<table id="querytableDatasets" class="display" cellspacing="0" 
cellpadding="3" width="100%" style="width: 0px;">

Looking in Firebug at the styles, the table.display style has been overridden. Can't see where this is coming from

element.style {  
  width:0;}    

-- dataTables.css (line 84
table.display { 
  margin:0 auto;  
  width:100%;  
}  

Jquery Solutions


Solution 1 - Jquery

jQuery('#querytableDatasets').dataTable({  
        "bAutoWidth": false
});

Solution 2 - Jquery

The issue is caused because dataTable must calculate its width - but when used inside a tab, it's not visible, hence can't calculate the widths. The solution is to call 'fnAdjustColumnSizing' when the tab shows.

Preamble

> This example shows how DataTables with scrolling can be used together > with jQuery UI tabs (or indeed any other method whereby the table is > in a hidden (display:none) element when it is initialised). The reason > this requires special consideration, is that when DataTables is > initialised and it is in a hidden element, the browser doesn't have > any measurements with which to give DataTables, and this will require > in the misalignment of columns when scrolling is enabled. > > The method to get around this is to call the fnAdjustColumnSizing API > function. This function will calculate the column widths that are > needed based on the current data and then redraw the table - which is > exactly what is needed when the table becomes visible for the first > time. For this we use the 'show' method provided by jQuery UI tables. > We check to see if the DataTable has been created or not (note the > extra selector for 'div.dataTables_scrollBody', this is added when the > DataTable is initialised). If the table has been initialised, we > re-size it. An optimisation could be added to re-size only of the > first showing of the table.

Initialisation code

$(document).ready(function() {
	$("#tabs").tabs( {
		"show": function(event, ui) {
			var oTable = $('div.dataTables_scrollBody>table.display', ui.panel).dataTable();
			if ( oTable.length > 0 ) {
				oTable.fnAdjustColumnSizing();
			}
		}
	} );
	
	$('table.display').dataTable( {
		"sScrollY": "200px",
		"bScrollCollapse": true,
		"bPaginate": false,
		"bJQueryUI": true,
		"aoColumnDefs": [
			{ "sWidth": "10%", "aTargets": [ -1 ] }
		]
	} );
} );

See this for more info.

Solution 3 - Jquery

You'll want to tweak two variables when you initialize dataTables: bAutoWidth and aoColumns.sWidth

Assuming you have 4 columns with widths of 50px, 100, 120px and 30px you would do:

jQuery('#querytableDatasets').dataTable({  
        "bPaginate": false,  
        "bInfo": false,  
        "bFilter": false,
        "bAutoWidth": false,
        "aoColumns" : [
            { sWidth: '50px' },
            { sWidth: '100px' },
            { sWidth: '120px' },
            { sWidth: '30px' }
        ]  
    }); 

More information on the initialization of dataTables can be found at http://datatables.net/usage

Watch for interaction between this setting of widhts and the CSS you are applying. You might comment your existing CSS before trying this to see how close you get.

Solution 4 - Jquery

Well, I'm not familiar with that plugin, but could you reset the style after adding the datatable? Something like

$("#querydatatablesets").css("width","100%")

after the .dataTable call?

Solution 5 - Jquery

I have had numerous issues with the column widths of datatables. The magic fix for me was including the line

table-layout: fixed;

this css goes with the overall css of the table. For example, if you have declared the datatables like the following:

LoadTable = $('#LoadTable').dataTable.....

then the magic css line would go in the class Loadtable

#Loadtable {
margin: 0 auto;
clear: both;
width: 100%;
table-layout: fixed;

}

Solution 6 - Jquery

TokenMacGuys solution works best becasue this is the result of a bug in jQdataTable. What happens is if you use $('#sometabe').dataTable().fnDestroy() the table width gets set to 100px instead of 100%. Here is a quick fix:

$('#credentials-table').dataTable({
		"bJQueryUI": false,
		"bAutoWidth": false,
		"bDestroy": true,
		"bPaginate": false,
		"bFilter": false,
		"bInfo": false,
	"aoColumns": [
           { "sWidth": "140px" },
           { "sWidth": "300px" },
           { "sWidth": "50px" }       
		],
		"fnInitComplete": function() {
			
			$("#credentials-table").css("width","100%");
		}
		
	});


	

Solution 7 - Jquery

You have to leave at least one field without fixed field, for example:

$('.data-table').dataTable ({

 "bAutoWidth": false,
 "aoColumns" : [
    null,
    null,
    null,                    
    null,
    {"sWidth": "20px"},
    { "sWidth": "20px"}]
});

You can change all, but leave only one as null, so it can stretch. If you put widths on ALL it will not work. Hope I helped somebody today!

Solution 8 - Jquery

As on Datatable 10.1, this is straight forward. Just put width attribute to your table in HTML. i.e. width="100%", this will override all CSS styles set by DT.

See this http://www.datatables.net/examples/basic_init/flexible_width.html

Solution 9 - Jquery

Add this css class to your page, it will fix the issue:

#<your_table_id> {
	width: inherit !important;
}

Solution 10 - Jquery

Setting widths explicitly using sWidth for each column AND bAutoWidth: false in dataTable initialization solved my (similar) problem. Love the overflowing stack.

Solution 11 - Jquery

"fnInitComplete": function() {
    $("#datatables4_wrapper").css("width","60%");
 }

This worked fine to adjust the whole table width. Thanks @Peter Drinnan!

Solution 12 - Jquery

None of the solutions here worked for me. Even the example on the datatables homepage did not work hence to the initialization of the datatable in the show option.

I found a solution to the problem. The trick is to use the activate option for tabs and to call fnAdjustColumnSizing() on the visible table:

$(function () {

// INIT TABS WITH DATATABLES
$("#TabsId").tabs({
    activate: function (event, ui) {
        var oTable = $('div.dataTables_scrollBody>table:visible', ui.panel).dataTable();
        if (oTable.length > 0) {
            oTable.fnAdjustColumnSizing();
        }
    }
});

// INIT DATATABLES
// options for datatables
var optDataTables = {
    "sScrollY": "200px",
    "bScrollCollapse": true,
    "bPaginate": false,
    "bJQueryUI": true,
    "aoColumnDefs": [
        { "sWidth": "10%", "aTargets": [-1] }
    ]
};
// initialize data table
$('table').dataTable(optDataTables);

});

Solution 13 - Jquery

Are you doing this in the ready event?

$(document).ready(function() { ... });
The sizing is most likely going to be dependent on the document being fully loaded.

Solution 14 - Jquery

Just to say I've had exactly the same problem as you, although I was just apply JQuery to a normal table without any Ajax. For some reason Firefox doesn't expand the table out after revealing it. I fixed the problem by putting the table inside a DIV, and applying the effects to the DIV instead.

Solution 15 - Jquery

Check this solution too. this solved my DataTable column width issue easily

JQuery DataTables 1.10.20 introduces columns.adjust() method which fix Bootstrap toggle tab issue

 $('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
    $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );

Please refer the documentation : Scrolling and Bootstrap tabs

Solution 16 - Jquery

For anyone having trouble adjusting table / cell width using the fixed header plugin:

Datatables relies on thead tags for column width parameters. This is because its really the only native html as most of the table's inner html gets auto-generated.

However, what happens is some of your cell can be larger than the width stored inside the thead cells.

I.e. if your table has a lot of columns (wide table) and your rows have a lot of data, then calling "sWidth": to change the td cell size won't work properly because the child rows are automatically resizing td's based on overflow content and this happens after the table's been initialized and passed its init params.

The original thead "sWidth": parameters get overridden (shrunk) because datatables thinks your table still has its default width of %100--it doesn't recognize that some cells are overflowed.

To fix this I figured out the overflow width and accounted for it by resizing the table accordingly after the table has been initialized--while we're at it we can init our fixed header at the same time:

$(document).ready(function() {
  $('table').css('width', '120%');
  new FixedHeader(dTable, {
	    "offsetTop": 40,
      });
});

Solution 17 - Jquery

create your fixedheader inside the "success" of your ajax call, you will not have any alignment problem in header and rows.

success: function (result) {
              /* Your code goes here */
        
    var table = $(SampleTablename).DataTable();

        new $.fn.dataTable.FixedHeader(table);
}        

Solution 18 - Jquery

Hope this helps someone who's still struggling.

Don't keep your table inside any container. Make the table's wrapper your container after the table's rendered. I know this might be invalid at places where you have something else along with the table but then you could always append that content back.

For me,this problem arises if you have a sidebar and a container that is actually an offset to that sidebar.

$(YourTableName+'_wrapper').addClass('mycontainer');

(I added a panel panel-default)
And your class :

.mycontainer{background-color:white;padding:5px;}

Solution 19 - Jquery

find another useful link about this problem and it resolved my problem.

<table width="100%">
<tr>
    <td width="20%"> Left TD <td>
    <td width="80%"> Datatable </td>
</tr>
</table>

https://stackoverflow.com/questions/30074910/datatables-force-width-table

Solution 20 - Jquery

I ran into a similar issue when having a div wrapped around the table.

Adding position: relative fixed it for me.


#report_container {
float: right;
position: relative;
width: 100%;
}

Solution 21 - Jquery

I had a similar issue where the contents of the table were bigger than the table header and footer. Adding a div around the table and setting x-overflow seems to have sorted this issue:

Solution 22 - Jquery

Be sure that all others parameters before bAutoWidth & aoColumns are correctly entered.Any wrong parameter before will break this functionality.

Solution 23 - Jquery

i had the similar problem and found that text in columns don't break and using this css code solved the problem

th,td{
max-width:120px !important;
word-wrap: break-word
}

Solution 24 - Jquery

This is my way of doing it..

$('#table_1').DataTable({
    processing: true,
    serverSide: true,
    ajax: 'customer/data',
    columns: [
        { data: 'id', name: 'id' , width: '50px', class: 'text-right' },
        { data: 'name', name: 'name' width: '50px', class: 'text-right' }
    ]
});

Solution 25 - Jquery

I Meet the same problem today.

I used a tricky way to solve it.

My Code as below.

$('#tabs').tabs({
    activate: function (event, ui) {
       //redraw the table when the tab is clicked
       $('#tbl-Name').DataTable().draw();
    }
});

Solution 26 - Jquery

This works fine.

#report_container {
   float: right;
   position: relative;
   width: 100%;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn MacView Question on Stackoverflow
Solution 1 - JquerySurajView Answer on Stackoverflow
Solution 2 - JqueryArik KfirView Answer on Stackoverflow
Solution 3 - JqueryartlungView Answer on Stackoverflow
Solution 4 - JquerySingleNegationEliminationView Answer on Stackoverflow
Solution 5 - Jqueryuser1842675View Answer on Stackoverflow
Solution 6 - JqueryPeter DrinnanView Answer on Stackoverflow
Solution 7 - Jquerycure85View Answer on Stackoverflow
Solution 8 - JqueryUditView Answer on Stackoverflow
Solution 9 - JqueryBahadir TasdemirView Answer on Stackoverflow
Solution 10 - JquerytubelightView Answer on Stackoverflow
Solution 11 - JqueryNilani AlgiriyageView Answer on Stackoverflow
Solution 12 - JqueryHelmut SteinerView Answer on Stackoverflow
Solution 13 - JqueryMufakaView Answer on Stackoverflow
Solution 14 - JqueryDaveView Answer on Stackoverflow
Solution 15 - JqueryPNPView Answer on Stackoverflow
Solution 16 - JqueryDrewTView Answer on Stackoverflow
Solution 17 - JqueryChandra Sekhar beluduruView Answer on Stackoverflow
Solution 18 - JqueryabcdefghirajView Answer on Stackoverflow
Solution 19 - JqueryChuanzhou TangView Answer on Stackoverflow
Solution 20 - JquerymardalaView Answer on Stackoverflow
Solution 21 - JqueryNick HoldenView Answer on Stackoverflow
Solution 22 - JqueryDejanRView Answer on Stackoverflow
Solution 23 - Jqueryh0mayunView Answer on Stackoverflow
Solution 24 - JqueryKevin KhewView Answer on Stackoverflow
Solution 25 - JqueryKenneth WongView Answer on Stackoverflow
Solution 26 - JquerySamView Answer on Stackoverflow