Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show more on click on table

Tags:

jquery

I have got to a stick point with my JQuery where I need some assistance, I am trying to create a show more on table rows but I want to show initially the first 10 and then load them by 10 at a time but at the moment its 1 and 1 at a time:

<script type="text/javascript">
var curr = 0;
var rowN = $('.table tr').length;

$('.table tr').eq(curr).siblings().hide(); // hide all but current one

$('a.load_more').on('click',function(e){
    e.preventDefault(); // prevent default anchor behavior    
    $('.table tr').eq(++curr).show();
});

</script>

I have tried to alter the current but it just starts at a certain row number and not row 1 so I want it to show the first ten and then on click loads the next ten and so on...

like image 993
PhpDude Avatar asked Mar 10 '23 15:03

PhpDude


2 Answers

A better solution which avoids the use of a global variable is to put a class on the shown rows. You can then use that class to find the index of the last visible element and show the next group of elements. Try this:

$('table tr:first').addClass('active');

$('a.load_more').on('click', function(e) {
  e.preventDefault();  
  var $rows = $('table tr');
  var lastActiveIndex = $rows.filter('.active:last').index();
  $rows.filter(':lt(' + (lastActiveIndex + 3) + ')').addClass('active');
  
  // hide the button when all elements visible
  $(this).toggle($rows.filter(':hidden').length !== 0);
});
table tr { display: none; }
table tr.active { display: table-row; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
  <tr><td>Row 4</td></tr>
  <tr><td>Row 5</td></tr>
  <tr><td>Row 6</td></tr>
  <tr><td>Row 7</td></tr>
  <tr><td>Row 8</td></tr>
  <tr><td>Row 9</td></tr>
  <tr><td>Row 10</td></tr>
</table>

<a href="#" class="load_more">Load more</a>

In the above sample it displays 2 further rows per click, but this can easily be amended as required.

like image 118
Rory McCrossan Avatar answered May 23 '23 01:05

Rory McCrossan


will this help? fiddle here

<table>
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>1</td>
  </tr> ..............
</table>


$(document).ready(function() {

  var pagelength = 10;
  var pageIndex = 1;
  //hide all tr greater than page length
  var selector = "tr:gt(" + pagelength + ")";
  $(selector).hide();

  $("#loadMore").click(function(){
    var itemsCount = ((pageIndex * pagelength) + pagelength);   
    var selector = "tr:lt(" + itemsCount + ")";
    $(selector).show();
    pageIndex++;
  });

});
like image 32
Developer Avatar answered May 23 '23 03:05

Developer