Hide table rows dynamically with jQuery

I am trying to alternate the background colors of the rows of a table, with each section starting with the same color. I achieved this with the following code:

$(document).ready(function(){ $("tbody tr.row:nth-child(even)").css("background", "#efefef"); });

I also need to limit the number of lines (e.g. 5) that are visible inside each part of the body. They should be able to switch using the button with the .click () event. Does anyone know how I can achieve this? The only solutions I came up with were blurring the background colors. Any help would be greatly appreciated!

Here is an example table structure:

<table>
    <tbody>
        <tr>
            <td>Cell Contents</td>
            <td>Cell Contents</td>
        </tr>
        <tr>
            <td>Cell Contents</td>
            <td>Cell Contents</td>
        </tr>
        <tr>
            <td>Cell Contents</td>
            <td>Cell Contents</td>
        </tr>
    </tbody>

    <tbody>
        <tr>
            <td>Cell Contents</td>
            <td>Cell Contents</td>
        </tr>
        <tr>
            <td>Cell Contents</td>
            <td>Cell Contents</td>
        </tr>
        <tr>
            <td>Cell Contents</td>
            <td>Cell Contents</td>
        </tr>
    </tbody>
</table>
+4
source share
3 answers

This should do the trick:

$(function() {
    $('#showAll').click(function() {
        $('table > tbody').each(function() {
            $(this).children('tr:gt(4)').toggle();
        });
        $("tr:visible").filter(':odd').css("background", "#efefef").end()
            .filter(':even').css("background", "#ffffff");
    }).click();
});

Edited to clear code (inspired by @ karim79 answer).

+2
source

This is it (tested):

var rowLimit = 5;
$(document).ready(function() {
     $('button').click(function() {
        //hide everything after the rowLimit row
        $('table > tbody > tr:gt(' + (rowLimit - 1) + ')').toggle();
     });
 });

gt

, CSS addClass removeClass, , , , :)

+1

scrolling. Set the height of the table into which 5 rows will fit, and then use css

overflow: scroll ;: D

0
source

All Articles