Stackoverflow Response: jquery- hide columns in table where there are rowspans
http://stackoverflow.com/questions/16156305/jquery-hide-columns-in-table-where-there-are-rowspans/16158187#16158187
by Terry Young
HTML
<table id="tbl" border="1" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="100%" cellpadding="0" cellspacing="0">
<tr>
<td rowspan=5>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td rowspan=3>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td rowspan=5>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td rowspan=3>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
<button name="toggle" value="1">Toggle Col 1</button><br>
<button name="toggle" value="2">Toggle Col 2</button><br>
<button name="toggle" value="3">Toggle Col 3</button><br>
<button name="toggle" value="4">Toggle Col 4</button><br>
<button name="toggle" value="5">Toggle Col 5</button><br>
JavaScript
$('button[name=toggle]').on('click', function () {
var iNthColumn = +$(this).val(), // cast to integer
$rows = $('#tbl tr'),
// key = which column, value = how much rowspan
shifts = {};
$rows.each(function (i, row) {
var $row = $(row),
n = iNthColumn;
// decrement 'n' for any instance of rowspans
// that have occured that is BEFORE the
// 'expected' column, i.e. iNthColumn
$.each(shifts, function (j, iShift) {
if (+j <= iNthColumn && shifts[iNthColumn] > 1) {
shifts[iNthColumn]--;
n--;
}
});
// Select the actual cell
// If it doesn't exist (because of rowspans
// that have occured that is AFTER the
// 'expected' column, i.e. iNthColumn,
// then $td would be empty, and the rest of the
// code below would just run silently and do nothing
var $td = $row.find('td:nth-child(' + n + ')');
var $prevAll = $td.prevAll().andSelf();
$prevAll.each(function (k, cell) {
var $cell = $(cell),
iShift = +$cell.attr('rowspan'); // cast to integer
if ( ! isNaN(iShift) && iShift > 1) {
shifts[iNthColumn] = iShift;
}
});
$td.toggle();
});
});