Legend Legend - 3 days ago 4
HTML Question

Collapsing table rows with multiple tbody elements

I have a table that looks like this:

<table>
<thead>
<tr><th>Customer</th><th>Order</th><th>Month</th></tr>
</thead>
<tbody>
<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>
</tbody>
<tbody>
<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>
</tbody>
<tbody>
<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>
</tbody>
....
.... 10s of records like this
</table>


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
Answer

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")) {
            $this.removeClass("collapsed");
            myTRs.first().remove();            
            myTRs.show();
        } else {
            $this.addClass("collapsed");
            var newInfo = myTRs.first().children("td").first().text() + " | " + myTRs.length + " entries";
            myTRs.hide();
            $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.

Comments