html - Change background color of column based on header text with colspan -
i trying solve similar problem answered here: https://stackoverflow.com/a/9541558/1933036.
i style cells in table based on specific header. resolved in above link, works single headers. header has colspan of 2 or more cause code not work. have demonstrated in forked version of working solution heading spanning multiple columns: https://jsfiddle.net/icarnaghan/apj2ady4/1/. 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 can see example, unable colorize cells both columns under heading 2. i'm not sure correct approach given problem, advice or tips appreciated.
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
Post a Comment