show / hide table columns using jQuery
http://stackoverflow.com/questions/15970382/show-hide-table-columns-using-jquery
by sunil puvvada
HTML
<table id="tableId">
<thead>
<tr>
<th>
<input id="chk1" type="checkbox" />
</th>
<th>
<input id="chk2" type="checkbox" />
</th>
<th>
<input id="chk3" type="checkbox" />
</th>
<th>
<input id="chk4" type="checkbox" />
</th>
<th>
<input id="chk5" type="checkbox" />
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<p>col1</p>
</td>
<td>
<p>col2</p>
</td>
<td>
<p>col3</p>
</td>
<td>
<p>col4</p>
</td>
<td>
<p>col5</p>
</td>
</tr>
<tr>
<td>
<p>col1</p>
</td>
<td>
<p>col2</p>
</td>
<td>
<p>col3</p>
</td>
<td>
<p>col4</p>
</td>
<td>
<p>col5</p>
</td>
</tr>
<tr>
<td>
<p>col1</p>
</td>
<td>
<p>col2</p>
</td>
<td>
<p>col3</p>
</td>
<td>
<p>col4</p>
</td>
<td>
<p>col5</p>
</td>
</tr>
<tr>
<td>
<p>col1</p>
</td>
<td>
<p>col2</p>
</td>
<td>
<p>col3</p>
</td>
<td>
<p>col4</p>
</td>
<td>
<p>col5</p>
</td>
</tr>
<tr>
<td>
<p>col1</p>
</td>
<td>
...
CSS
th, td { padding: .2em .7em; text-align: center; width: 40px; }
JavaScript
$(function() {
$("#tableId input[type=checkbox]").on("change", function(e) {
var id = $(this).parent().index()+1,
col = $("table tr td:nth-child("+id+") p");
$(this).is(":checked") ? col.show() : col.hide();
}).prop("checked", true).change();
$("button").on("click", function(e) {
$("input[type=checkbox]").prop("checked", true).change();
});
})