Pramod Karandikar
Pramod Karandikar

Reputation: 5329

Show only a limited number of rows in a table

I am trying to limit the number of rows displayed in a <table>. I need to show only 2 rows out of whatever number of records fetched. There's a small button at the end of the table, on click of which the rest of the records will get revealed.

Here's a sample screenshot of how the table will look like. enter image description here

I have tried searching over SO and other websites, but unable to get through. I can't use any jQuery plugin for table either.

How can I achieve this using jQuery/JavaScript?

Upvotes: 5

Views: 9295

Answers (3)

Emma Patterson
Emma Patterson

Reputation: 21

This is how I did it:

<script>
        $(document).ready(function () {
            $('table tr:gt(10)').hide();


        });
        function showAllRows() {
            $('table tr').show();
        }

    </script>

Then the button for show all:

<button onclick="showAllRows()">Show all</button>

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113507

Select tr elements from tbody and use slice method to select a range of them:

$("table > tbody > tr").hide().slice(0, 2).show();

Demo:

$("table > tbody > tr").hide().slice(0, 2).show();
$(".show-all").on("click", function() {
  $("tbody > tr", $(this).prev()).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>1</td>
      <td>Alice</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Bob</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Carol</td>
    </tr>
  </tbody>
</table>
<button class="show-all">Show all</button>


.slice( start [, end ] )

Reduce the set of matched elements to a subset specified by a range of indices.

  • start

    Type: Integer

    An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.

  • end

    Type: Integer

    An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.

Upvotes: 8

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can use :gt selector to target other rows having index greater than 2 and then hide them:

$('table tr:gt(1)').hide();// :gt selector has 0 based index

Upvotes: 2

Related Questions