'Datatable column width issue after "refresh" row data
I'm currently using datatable to produce table below:
I'm happy with the result as the width of each column is calculated automatically, resulting 1 line per row, looks awesome. The table above is generated via API, by using simple code below:
var dataTable;
// This is the button with text "Filter" as shown in screenshot
$('#search').click(function(e) {
e.preventDefault();
if (dataTable) {
dataTable.clear();
dataTable.destroy();
}
$.ajax({
type : "GET",
url : contextPath + "/api/company/list",
contentType : "application/json;charset=utf-8",
data : { token : token(), name: $('#name').val() },
success : function(data) {
if (data) {
var tag = '';
for (var i = 0; i < data.length; i++) {
var c = data[i];
tag += '<tr>'
+ '<td>' + (i + 1) + '</td>'
+ '<td>' + c.name + '</td>'
+ '<td>' + c.registrationNumber + '</td>'
+ '<td>' + c.createdTime + '</td>'
+ '<td>'
+ ' <a href="' + contextPath + '/company?id=' + c.id + '" target="_blank"><i class="fa fa-fw fa-search text-info"></i></a>'
+ ' <a href="' + contextPath + '/company/update?id=' + c.id + '"><i class="fa fa-fw fa-edit text-warning"></i></a>'
+ '</td>'
+ '</tr>';
}
$('#tableBody').html(tag);
dataTable = $('#tableBody').parent().DataTable();
} else {
alert("Oops, there's an error! Please reload the page");
}
}, error : function(xhr) {
alert("Oops, there's an error! Please reload the page");
console.log(xhr);
}
});
});
Snippet of table html:
<div class="card-body">
<div class="table-responsive">
<table class="table data-table">
<thead class=" text-primary">
<th>#</th>
<th>Name</th>
<th>Registration Number</th>
<th>Date Created</th>
<th></th>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>
</div>
However, problem arise when I click the filter button and re-run the same onClick function, the table column will be somehow resize and looks below:
The width of each column is resized resulting 3 lines per row, subsequent clicks on Filter button will remain in this format. Anybody know how to avoid this column width recalculation thing?
Solution 1:[1]
Apparently this happens because datatables assign the width attribute to all th.
Adding the autoWidth false property prevents that.
$('#tableBody').parent().DataTable({"autoWidth": false});
And the width calculation is then automated by web browser (eg chrome)
Solution 2:[2]
$('#example').dataTable( {
"autoWidth": false, // might need this
"columns": [
{ "width": "20%" },
null, // automatically calculates
null // remaining width
]
} );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chor Wai Chun |
Solution 2 | Mohammad I |