Skip to content Skip to sidebar Skip to footer

Checkboxes Hide Groups Of Rows From A Table

I have a table that I would like to dynamically hide/reveal rows in, based on checkboxes at the top. I would like to do this without jQuery, just vanilla Javascript. I have seen n

Solution 1:

Given HTML like the following:

<table>
    <thead>
        <tr>
            <td>
                <label>
                    <input type="checkbox" class="show" value="north" checked />North</label>
            </td>
        </tr>
        <tr>
            <td>
                <label>
                    <input type="checkbox" class="show" value="south" checked />South
                </label>
            </td>
        </tr>
        <tr>
            <td>
                <label>
                    <input type="checkbox" class="show" value="outOfArea" checked />Out of area
                </label>
            </td>
        </tr>
    </thead>
    <tbody>
        <tr class="north">
            <td>North One</td>
        </tr>
        <tr class="north">
            <td>North Two</td>
        </tr>
        <tr class="outOfArea">
            <td>Out-of-area One</td>
        </tr>
        <tr class="south">
            <td>South One</td>
        </tr>
        <tr class="south">
            <td>South Two</td>
        </tr>
        <tr class="north">
            <td>North Three</td>
        </tr>
        <tr class="north">
            <td>North Four</td>
        </tr>
        <tr class="south">
            <td>South Three</td>
        </tr>
        <tr class="outOfArea">
            <td>Out-of-area Two</td>
        </tr>
    </tbody>
</table>

The following jQuery seems to do as you seem to describe:

$('thead input[type=checkbox]').change(function(){
    var self = this;
    $(self).closest('table').find('tbody tr').filter('.' + self.value).toggle(self.checked);
});

JS Fiddle demo.

As it seems that you'd prefer a plain-JavaScript approach, I'd suggest the following (to work on the same HTML as posted above):

function toggle (e) {
    var self = e.target,
        toggleClass = '.' + self.value,
        toToggle = document.querySelectorAll(toggleClass);
    for (var i = 0, len = toToggle.length; i < len; i++) {
        toToggle[i].style.display = self.checked ? 'table-row' : 'none';
    }
}

var thead = document.querySelector('thead');
thead.addEventListener('change', toggle);

JS Fiddle demo.

References:


Solution 2:

Looks like you are describing something along the lines of this example


Post a Comment for "Checkboxes Hide Groups Of Rows From A Table"