Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle visibility of additional table rows

I have a table for which I want to display only the first row by default, but display additional X number of rows if a user clicks a "show more" link (and inversely hide the X rows if the user then clicks "show less").

To exemplify, I want the default view when the page loads to be like so:

 Top Scores
====================================
|   1 | show this row always!      |
====================================
 -show more-

Then, if a user clicks "show more", the table should expand with additional rows and look like this:

 Top Scores
====================================
|   1 | show this row always!      |
|   2 | newly displayed row        |
|   3 | newly displayed row        |
|   4 | newly displayed row        |
|   5 | newly displayed row        |
====================================
 -show less-

Then obviously if a user clicks "show less" the table returns to default (showing only the first row again).

I'm familiar with the .toggle() function in jQuery, but not sure if it can be applied here or if I have to do more manual work.

Thanks!

like image 710
hannebaumsaway Avatar asked Jun 22 '12 16:06

hannebaumsaway


3 Answers

No additional classes, no headers required - http://jsfiddle.net/wgSZs/

$('table').find('tr:gt(0)').hide();

$("button").on("click", function() {
    $('table').find('tr:gt(0)').toggle();
});

UPDATE

It might be better to hide the additional rows via CSS instead of jQuery to avoid element shifting while the JS is being downloaded and applied. But still no need to add classes - it's a good idea to keep your markup as clean as possible. You can do this:

table tr { display: none }
table tr:first-child { display: block }

Here is the working example - http://jsfiddle.net/wgSZs/1/

like image 153
Zoltan Toth Avatar answered Nov 14 '22 04:11

Zoltan Toth


if you mark the added rows with a class like .collapsible, then you can easily toggle their visibility in javascript.

$('.collapsible').show() or $('.collapsible').hide() or $('.collapsible').toggle()

like image 2
Kristian Avatar answered Nov 14 '22 03:11

Kristian


http://jsfiddle.net/iambriansreed/uwfk8/

var initial_rows_to_show = 2;

(function(_rows){    
    _rows.hide();
    $('a.more').toggle(function(){
        _rows.show(); $(this).text('less');
    },function(){    
        _rows.hide(); $(this).text('more');
    });
})($('tr:gt(' + (initial_rows_to_show - 1) + ')'));
like image 1
iambriansreed Avatar answered Nov 14 '22 04:11

iambriansreed