0

I have a table with some long texts and some short texts. If a <td> contains a long text I would like to increase the width.

This is what I tried to do:

var text = $('td').text().split('\n');
if(text.length === 1) {
    $(this).css('width','270px');
}

jsFiddle
I tried to get the number of line breaks with alert(text.length) and i get 1. Then if there is 1 line break I added .css('width','270px'), but doesn't work. What I did wrong?

Thanks for help!

Mustapha Aoussar
  • 5,833
  • 15
  • 62
  • 107

2 Answers2

2

I took a stab at what I think you are trying to do:

var $tds = $('td');

$tds.each(function(){

    var $td = $(this), length = $.trim($td.text()).length;

    if( length > 22 ) {
        $td.css('background-color', 'red');
    }

});

If not this should get you a lot closer to your goal. Here's an updated fiddle: http://jsfiddle.net/dsc4m/6/

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
2

From your fiddle I guess that you cannot use split('\n') to detect if the text breaks into multiple lines because those line breaks are automatically inserted by the browser for layout purposes and they don't exist as \n in the text.

I would suggest to compare the rendered height of the cell to calculate the number of lines inside.

UPDATE

Thanks Bill, that was a good point. The cells in each row are always of equal height. The first solution that came to my mind was to use wrapper divs inside the cells. They only expand as much as needed to display the text. It's not "nice" but it seems to do the job: http://jsfiddle.net/dsc4m/7/

RobDil
  • 4,036
  • 43
  • 52
  • Ah, another interesting hypothesis! – Bill Criswell Dec 09 '13 at 14:46
  • Nice to hear it helped you. I was wondering why you didn't go for auto-layout on this table...? The browser expands the line if necessary. – RobDil Dec 09 '13 at 14:50
  • 1
    I just tried updating my answer... All the cells heights would be the same. You might need to do it based on the amount of characters in the cell's text. – Bill Criswell Dec 09 '13 at 14:50
  • @ToniTornado Here's my little fiddle if you care to mess around with it to update your answer since it's marked as accepted. http://jsfiddle.net/dsc4m/6/ – Bill Criswell Dec 09 '13 at 14:53
  • @Bill I don't think you can use the number of characters. Consider WWWWWWW and lllllll are of the same length. This question is about getting the length in pixels: http://stackoverflow.com/questions/2057682/determine-pixel-length-of-string-in-javascript-jquery – RobDil Dec 09 '13 at 15:04
  • Agreed. I think the wrapper div is sadly a better approach that still stinks. – Bill Criswell Dec 09 '13 at 15:06