Reputation: 637
I'm using 2 tables to create a scroll-able table. But they are 2 separated tables and the column width do not match. How to get the column width from tbody and apply it to thead?
<div>
<table id="header">
<thead>
<tr>
<td>header 1</td>
<td>header 2</td>
<td>header 3</td>
<td>header 4</td>
</tr>
</thead>
</table>
</div>
<div class="scrollable">
<table id="body">
<tbody>
<tr>
<td>data 1-1</td>
<td>1-2</td>
<td>data 1-3</td>
<td>data 1-4</td>
</tr>
<tr>
<td>data 2-1</td>
<td>2-2</td>
<td>data 2-3</td>
<td>data 2-4</td>
</tr>
<tr>
<td>data 3-1</td>
<td>3-2</td>
<td>length testing</td>
<td>data 3-4</td>
</tr>
<tr>
<td>data 4-1</td>
<td>short</td>
<td>data 4-3</td>
<td>data 4-4</td>
</tr>
</tbody>
</table>
</div>
Thank you in advance.
Upvotes: 0
Views: 78
Reputation: 1462
This should give you what you are looking for. The table width also has to be matched up.
//match the table width
$("#header").width($("#body").width());
var bodyTr = $("#body tr:first td");
$("#header tr:first td").each(function(index, value) {
$(this).width(bodyTr.eq(index).width());
});
Here is your modified fiddle: https://jsfiddle.net/3L17sgjw/4/
Upvotes: 1
Reputation: 34
You can set a class for every column with something like this:
$("#header td:nth-of-type(1)").addClass("column1");
$("#body td:nth-of-type(1)").addClass("column1");
//And so with every column you want
And then set the fixed width value for that class. The correct way of doing this would be with a for loop to do not duplicate the same two lines for every column.
But i think that it would be easier if you just add your 'scrollable' class to the tbody without keeping thead and tbody separated in different divs.
Upvotes: 0