I have the following code, which hides columns dynamically. The problem is that I am trying to add a colspan for the first column, which contains 2 columns. If I hide the first one, only the first one that is inside it and not the second one is hidden, unraveling my table .. Can someone help me out please? thanks.
$(document).on("click", "[data-column]", function () {
var button = $(this),
header = $(button.data("column")),
table = header.closest("table"),
index = header.index() + 1, // convert to CSS's 1-based indexing
selector = "tbody tr td:nth-child(" + index + ")",
column = table.find(selector).add(header);
column.toggleClass("hidden");
});
.hidden { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<th id="column-a" colspan="2">Step 1</th>
<th id="column-b" colspan="1">Step 2</th>
<th id="column-c" colspan="1">Step 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Of step 1</td>
<td>Of step 1</td>
<td>Of step 2</td>
<td>Of step 3</td>
</tr>
<tr>
<td>Of step 1</td>
<td>Of step 1</td>
<td>Of step 2</td>
<td>Of step 3</td>
</tr>
</tbody>
</table>
<button type="button" data-column="#column-a">Hide/show 1st</button>
<button type="button" data-column="#column-b">Hide/show 3rd</button>
<button type="button" data-column="#column-c">Hide/show last</button>