Legend Legend - 1 month ago 16
HTML Question

Collapsing table rows with multiple tbody elements

I have a table that looks like this:

<tr><td>Customer 1</td><td>#1</td><td>January</td></tr>
<tr><td>Customer 1</td><td>#2</td><td>April</td></tr>
<tr><td>Customer 1</td><td>#3</td><td>March</td></tr>
<tr><td>Customer 2</td><td>#1</td><td>January</td></tr>
<tr><td>Customer 2</td><td>#2</td><td>April</td></tr>
<tr><td>Customer 2</td><td>#3</td><td>March</td></tr>
<tr><td>Customer 3</td><td>#1</td><td>January</td></tr>
<tr><td>Customer 3</td><td>#2</td><td>April</td></tr>
<tr><td>Customer 3</td><td>#3</td><td>March</td></tr>
.... 10s of records like this

I want to make each tbody element clickable (collapsible) so that in a collapsed state, I would get a summary of what is inside (say,
Customer 1 | 3 Entries
) and in an expanded state, I would get to see the actual rows.

Can this be done for the table structured as shown above?

JSFiddle here: http://jsfiddle.net/Ju4xH/

Ian Ian

It's a little messy and the animations don't work (I'm guessing it's because it's on the <tr>s, but here's what I came up with:

$(document).ready(function () {
    $("table").on("click", "tbody", function () {
        var $this = $(this);
        var myTRs = $this.children("tr");

        if ($this.hasClass("collapsed")) {
        } else {
            var newInfo = myTRs.first().children("td").first().text() + " | " + myTRs.length + " entries";
            $this.prepend($("<tr><td colspan='3'>" + newInfo + "</td></tr>").hide()).find("tr").first().slideDown();

DEMO: http://jsfiddle.net/ZhqAf/1/

When you click a non-collapsed <tbody>, it will hide the rows and prepend a new one with the details you wanted. When you click a collapsed <tbody>, it removes the new "details" row, and shows the original rows.