Show only a limited number of rows in a table.
I am trying to limit the number of lines displayed in <table>
. I only need to show 2 lines from any number of loaded records. There's a small button at the end of the table that will reveal the rest of the records when clicked.
Here is an example screenshot of how the table will look.
I tried searching SO and other sites but couldn't get through. I can't seem to use any jQuery plugin for the table.
How can I achieve this with jQuery / JavaScript?
source to share
Select tr
items from tbody
and use the method slice
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 items to the subset specified by the range of indices.
start
Type: whole
An integer specifying the 0-based position at which items begin to be selected. If the value is negative, it indicates the offset from the end of the set.
end
Type: whole
An integer indicating the position, based on 0, at which the elements stop. If the value is negative, it means an offset from the end of the set. If omitted, the range continues to the end of the dial.
source to share