Show/hide table columns with jquery

by Annie Lagang

HTML

<a href="edit" id=edit>Edit table</a>
<table id=table>
<thead> 
    <tr>
        <th id="name">Name</th>
        <th id="street">Street</th>
        <th id="number">Number</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>
</table>

CSS

#tableEditor {
    position: absolute;
    left: 20px; top: 20px;
    padding: 5px;
    border: 1px solid #000;
    background: #fff;
}

body, th, td {
    font: normal 10pt Verdana;
}

table {
    border-collapse: collapse;
    margin: 1em 0 0 0;
}

th,td {
    text-align: left;
    border: 1px solid #ccc;
    padding: 2px 5px 2px 2px;
}

JavaScript

$('#edit').click(function() {
    var headers = $('#table th').map(function() {
        var th =  $(this);
        return {
            text: th.text(),
            shown: th.css('display') != 'none'
        };
    });
    
    var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
    $.each(headers, function() {
        h.push('<th><input type=checkbox',
               (this.shown ? ' checked ' : ' '),
               '/> ',
               this.text,
               '</th>');
    });
    h.push('</tr></thead></table></div>');
    $('body').append(h.join(''));
    
    $('#done').click(function() {
        var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
        $.each(showHeaders, function(i, show) {
            var cssIndex = i + 1;
            var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
            if (show)
                tags.show();
            else
                tags.hide();
        });
        
        $('#tableEditor').remove();
        return false;
    });
    
    return false;
});