Raven Raven - 2 years ago 80
jQuery Question

How to create a partially expanding/collapsing html table?

I am trying to improve on an old school "Top Screens" page that we currently have. It shows the top 30 in a plain old html table. I want to be able to generate the table with the top 100, but only show the top 20 on page load and then have an expand/collapse button. I have found plenty of examples of fully expanding and collapsing tables and subtables, but I have yet to find an example of partially doing one like I need.

It is currently a very simple 2 column table with headers and minimal CSS styling and JS. I would like to keep it to plain JS if possible, but I do have the JQuery library available to me, I am just not very familiar with it.

Any help would be appreciated.
Thanks in advance!


I apologize for what ended up being a simple solution with JQuery, but I am very new to it. After reading through the API docs some more I found the :gt() selector that when combined with toggle() lead to a very simple solution.

I add the "collapse" class to my <tbody> so the <thead> would not be affected or counted.

// Hide extra rows on load.
$(document).ready(function() {

// Toggle extra rows on click.

Answer Source

The simplelest way to do this would be with jQuery, as you could use the .toggle() method.

In my example I've chosen to only show the first 3 results, so that the code isn't too long.

See my comments in the code to understand what's going on.

$(document).ready(function() {
  $("button#sh").click(function() {

//Here jQuery listens for a click on the button with id "sh", and when clicked, 
//either shows or hides the rows selected by the CSS selector, which is the same as 
//the one that hid the rows in the CSS section.
tr.row:nth-child(n+5) {
  display: none
/* Here all rows after the 4th one will be hidden on load. So you have 1 row for the 
header, then 3 rows of data, 3+1=4, so row 5 and on will be hidden. */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Here jQuery is included -->

<button id="sh">Show/Hide</button>
<!-- Here the button that will show and hide the rows is set. -->

<table border="1">
  <tr class="row">
  <tr class="row">
    <td>Name 1</td>
  <tr class="row">
    <td>Name 2</td>
  <tr class="row">
    <td>Name 3</td>
  <tr class="row">
    <td>Name 4</td>
  <tr class="row">
    <td>Name 5</td>
  <tr class="row">
    <td>Name 6</td>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download