Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top