Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the corresponding table column (td) from a table header (th)?

I want to get the entire column of a table header.

For example, I want to select the table header "Address" to hide the address column, and select the "Phone" header to show the correspondent column.

<table>
<thead> 
    <tr>
        <th id="name">Name</th>
        <th id="address">Address</th>
        <th id="address" class='hidden'>Address</th>
    </tr>
</thead> 
<tbody>
    <tr>
        <td>Freddy</td>
        <td>Nightmare Street</td>
        <td class='hidden'>123</td>
    </tr>
    <tr>
        <td>Luis</td>
        <td>Lost Street</td>
        <td class='hidden'>3456</td>
    </tr>
</tbody>

I want to do something like http://www.google.com/finance?q=apl (see the related companies table) (click the "add or remove columns" link)

like image 912
panchicore Avatar asked Nov 15 '11 20:11

panchicore


2 Answers

Something like this would work -

$('th').click(function() {
    var index = $(this).index()+1;
    $('table td:nth-child(' + index + '),table th:nth-child(' + index + ')').hide()
});

The code above will hide the relevant column if you click on the header, the logic could be changed to suit your requirements though.

Demo - http://jsfiddle.net/LUDWQ/

like image 145
ipr101 Avatar answered Oct 05 '22 23:10

ipr101


With a couple simple modifications to your HTML, I'd do something like the following (framework-less JS):

HTML:

<input class="chk" type="checkbox" checked="checked" data-index="0">Name</input>
<input class="chk" type="checkbox" checked="checked" data-index="1">Address</input>
<input class="chk" type="checkbox" checked="checked" data-index="2">Phone</input>

<table id="tbl">
<thead> 
    <tr>
        <th>Name</th>
        <th>Address</th>
        <th>Phone</th>
    </tr>
</thead> 
<tbody>
    <tr>
        <td>Freddy</td>
        <td>Nightmare Street</td>
        <td>123</td>
    </tr>
    <tr>
        <td>Luis</td>
        <td>Lost Street</td>
        <td>3456</td>
    </tr>
</tbody>

Javascript:

var cb = document.getElementsByClassName("chk");
var cbsz = cb.length;

for(var n = 0; n < cbsz ; ++n) {
    cb[n].onclick = function(e) {
        var idx = e.target.getAttribute("data-index");
        toggleColumn(idx);
    }
}

function toggleColumn(idx) {
    var tbl = document.getElementById("tbl");
    var rows = tbl.getElementsByTagName("tr");
    var sz = rows.length;

    for(var n = 0; n < sz; ++n) {
        var el = n == 0 ? rows[n].getElementsByTagName("th")[idx] : rows[n].getElementsByTagName("td")[idx];
        el.style.display = el.style.display === "none" ? "table-cell" : "none";
    }
}

http://jsfiddle.net/dbrecht/YqUNz/1/

I added the checkboxes as it doesn't make sense to bind the click to the column headers as you won't be able to toggle the visibility, only hide them.

like image 28
Demian Brecht Avatar answered Oct 05 '22 22:10

Demian Brecht