Maki
Maki

Reputation: 637

how to find table column width and apply to another table in the same page

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>

jsfiddle

Thank you in advance.

Upvotes: 0

Views: 78

Answers (2)

Paul Zepernick
Paul Zepernick

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

Manuel Romero
Manuel Romero

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

Related Questions