Ian Carnaghan Ian Carnaghan - 28 days ago 7
HTML Question

Change background color of column based on header text with colspan

I am trying to solve a similar problem that was answered here: http://stackoverflow.com/a/9541558/1933036.

I would like to style cells in my table based on a specific header. This was resolved in the above link, however it only works with single headers. Any header that has a colspan of 2 or more will cause this code not to work. I have demonstrated this in forked version of the working solution with a heading spanning multiple columns: https://jsfiddle.net/icarnaghan/apj2ady4/1/. The same code follows.

<table border="1">
<thead>
<tr>
<th>Header 1</th>
<th colspan="2">Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 3</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 2, cell 3</td>
</tr>
</tbody>
</table>

var txt = 'Header 2';
var column = $('table tr th').filter(function() {
return $(this).text() === txt;
}).index();

if(column > -1) {
$('table tr').each(function() {
$(this).find('td').eq(column).css('background-color', '#ccc');
});
}


As you can see from my example, I am unable to colorize the cells for both columns under heading 2. I'm not sure this would even be the correct approach given my problem, however any advice or tips would be greatly appreciated.

Answer

Try this.

var txt = 'Header 2';
var column = $('table tr th').filter(function() {
    return $(this).text() === txt;
}).index();
//alert( $('table tr').find('th').eq(1).attr('colspan'));
var count=$('table tr').find('th').eq(column).attr('colspan');
//alert(count);
if(column > -1) {
    $('table tr').each(function() {
var trObj=$(this);
//alert(trObj);
        $(this).find('td').eq(column).css('background-color', '#ccc');

for(var lpvar=column;lpvar<=count;lpvar++)
{
//alert(trObj.find('td').eq(lpvar).text());
    trObj.find('td').eq(lpvar).css('background-color', '#ccc');
}
    });
}
Comments