user1713997
user1713997

Reputation: 3

jQuery table width of title

I have a table with short title but long cells (td). Is it possible to make the columns width to the smallest possible width of title ?

Example:

<table>
    <tr>
        <th>Name</th>
        <th>phone</th>
    </tr>
    <tr>
        <td>Santa</td>
        <td>20938570987098709870298349082456</td>
    </tr>
</table>

So, the column "phone" should show "20....."

Is it possible?

Upvotes: 0

Views: 104

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191779

A bit tougher if you need to be exact on the width and you're not using a monospace font.

$("th").each(function () {
   var chars = $(this).text().length;
   $("td").eq($(this).index()).each(function () {
      if ($(this).text().length > chars) {
         $(this).text($(this).text().substring(0, chars) + '...');
      }
   });
});

Not tested or optimized; just a proof-of-concept.

Upvotes: 1

Related Questions