My dilemma involves managing two tables:
In the scenario, Table 1 remains fixed in place serving as a header that is always visible. Meanwhile, Table 2 acts as the data table.
I am not a fan of fixed widths for my tables; I prefer them to dynamically adjust based on content. To achieve this flexibility, and considering the range of columns I may have (anywhere from 1 to 40), I cannot use a fixed width approach.
The issue lies in the misalignment of the table columns - they are nowhere near being properly aligned!?
Here is an overview of the HTML structure:
<!-- The Header Table with Fixed Position -->
<table class="table table-bordered table-condensed navbar navbar-fixed-top nowrap header">
<tr>
<td><input type="text" size="1" /></td>
<td><input type="text" size="1" /></td>
</tr>
<tr>
<td>Field 1</td>
<td>Field 2</td>
</tr>
</table>
<!-- The Data Table -->
<table class="table table-bordered table-hover table-condensed nowrap data">
<tr>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td> .... [CUT]
</table>
Now, here's the Javascript/jQuery logic:
// Determining the final layout for the table (the widest column takes precedence)
var arrLayout = [];
// Retrieving the column widths from the first row of the "header" table
$(".header tr:first").find("td").each(function() {
var index = $(this).index();
var width = $(this).width();
arrLayout[index] = width;
});
// Obtaining the column widths from the first row of the "data" table
$(".data tr:first").find("td").each(function() {
var index = $(this).index();
var width = $(this).width();
// Overriding the final layout if a larger column is found
if(width > arrLayout[index]) {
arrLayout[index] = width;
}
});
// Calculating the total table width
var widthSum = 0;
for(var i=0; i < arrLayout.length; i++) {
widthSum += arrLayout[i];
}
// Applying the newly calculated width to both tables
$(".header").width(widthSum);
$(".data").width(widthSum);
// Adjusting the widths of the columns in both tables
for(var i=0; i < arrLayout.length; i++) {
$(".header tr:first td:eq("+i+")").width(arrLayout[i]);
$(".data tr:first td:eq("+i+")").width(arrLayout[i]);
}
Take a look at the Fiddle demo. Make sure to press ENTER in one of the search boxes to see the new widths in action.
Any assistance on how to properly align the columns across the two tables would be greatly appreciated!