jQuery can be unbelievably handy and concise

Adding selectable table rows in jQuery

The short bit of jQuery consists of the following:
  • Adds a .click() function to any tr elements inside a tbody element to toggle the addition of the selected class whenever a row is clicked.
  • Next, another .click() to give a link with the ID selectAll the ability to toggle all rows at once.
  • Finally, one more .click() attached to the ID clearSelected that will deselect any rows currently selected.
In this case any tr elements inside a tbody element are selected, but this could be refined using IDs or Classes if there are multiple tables on the page.

$(document).ready(function() {
    $('tbody tr').click(function() {
        $(this).toggleClass('selected');
    });
    $('#selectAll').click(function() {
        $('tbody tr').toggleClass('selected');
    });
    $('#clearSelected').click(function() {
        $('tbody tr').removeClass('selected');
    });
});


The HTML for each button just needs to reference the chosen ID. A bit of CSS can make it look more like a button than a bog standard link if you're so inclined (I certainly was...)

<a href='#' id='selectAll' class='button'>Select All</a>
<a href='#' id='clearSelected' class='button'>Clear Selected</a>

Comments

Popular posts from this blog

Change the ComputerName value in Unattend.xml using PowerShell

Testing out Link Aggregation

Adding 802.1Q Trunking to Debian GNU/Linux