0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • duplicate of: http://stackoverflow.com/questions/4637942/how-can-i-truncate-a-string-in-jquery ? – Khôi Oct 02 '12 at 10:06

1 Answers1

1

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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405