Alright so first of all, since table is constructed as rows with cells, in order to select the whole column you need to use :nth-of-type
selector on all of the rows together to select their cells individually.
$('table td:nth-of-type(1),table th:nth-of-type(1)');
note that we select both <td>
and <th>
to select the header as well.
now, if you only need a hide functionality, you can indeed add a button to every column for hiding purpose:
$(function () {
$('table th').each(function () {
$('<button>Hide</button>').appendTo($(this)).click(function () {
var column_index = $(this).parent().index()+1;
$('table td:nth-of-type('+column_index+'),table th:nth-of-type('+column_index+')').hide();
});
});
});
Example 1
if however, ou need the ability to show the columns again, you need to place the buttons separately or they will disappear together with the columns.
you can for example, put a text box where you would specify the index of the column to hide/show as follows:
add to html:
<input id="col_hide" placeholder="insert col index 1+"></input>
<input type="submit" id="bt_hide" value="hide/show" />
js:
$(function () {
$('#bt_hide').click(function () {
var column_index = $('#col_hide').val();
$('table td:nth-of-type(' + column_index + '),table th:nth-of-type(' + column_index + ')').toggle();
});
});
Example 2
or if you want your table to be more user-friendly, you can create a button per column outside of the table:
js:
$(function () {
$('table th').each(function (_id, _value) {
$('<button>Toggle ' + parseInt(_id + 1) + '</button>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
});
});
Example 3