Iain Simpson
Iain Simpson

Reputation: 469

Hide a table column using jQuery

I am trying to hide a table column of a table with jQuery but am not really sure on how to do it. I have a drop down for each column and have two options, hide and show, on hide I would like column 0 to be hidden using the .hide() function I presume, and also shown when show is selected?

Upvotes: 2

Views: 8156

Answers (2)

Jasper
Jasper

Reputation: 75993

var $col_select = $('#col-select'),
    $opt_select = $('#opt-select'),
    $my_table   = $('table');
$col_select.add($opt_select).on('change', function () {
    var col_val = $col_select.children(':selected').val(),
        opt_val = $opt_select.children(':selected').val();
    if (col_val !== '' && opt_val !== '') {
        $my_table.find('td:nth-child(' + col_val + ')').css('display', opt_val);
    }
});

Here is a demo: http://jsfiddle.net/RjXpq/2/

Upvotes: 1

Rob W
Rob W

Reputation: 348972

The :nth-child pseudo-selector selects elements based on their position. If you want to select the, say, 5th column, you can use $("td:nth-child(5)").

An implementation could look like:

$("#mytable td:nth-child(5)").hide(); //or .hide(), or .toggle()

Upvotes: 7

Related Questions