How to make a collapsible HTML table using jQuery

October 15th, 2012 by admin Leave a reply »

I didn’t realize it, but when you are using an HTML table apparently anything inside your <Table> tags have to be either in a <tr> or <td>, it just simply ignores things like divs, so this didn’t allow me to just use the accordion collapsing goodness that Twitter’s bootstrap provides for me, so I had to come up with a way to get that work with tables, so here is the method that works.  First you start off with a simple table like so:

<table id="collapsibleTable">
            <thead>
            <tr>
                <th>Your Heading</th>
            </tr>
            </thead>
            <tr>
            <td>
               <label>Label to Show</label>
               <input id="yourId"></input>
               </td>
            </tr>
        </table>

Notice the label in the <td> item, this is a holder for the information when you aren’t clicked on the row of the table, below I have posted in the Javascript that does the magic using Jquery:

refreshTable: function (element) {
                $('#collapsibleTable').find('label').show();
                $('#collapsibleTable').find('div').hide();
                $('#collapsibleTable').find('input').hide();
                $('#collapsibleTable').find('select').hide();

                $(element).find('input').show();
                $(element).find('div').show();
                $(element).find('select').show();
                $(element).find('label').hide();
            }

As you can see, I use the find() method in JQuery to locate any inputs or labels or divs or even selects in the table and either hide or show them, depending on where you are in the table.  This is a bit of a hack, but it does work, it doesn’t provide the nice transition that bootstrap’s accordion does, but its is a nice way to keep your tables clean, I hope this helps someone, thanks.

Advertisement

Leave a Reply