Search code examples
jqueryhtml-tablerowscycle

Jquery Cycle through table rows


I need to set up jQuery to cycle through table rows. The table should always show only one row. When I click the link, the previous row or the next row should be shown.

The basic HTML structure is:

<div>
<a href="">Next</a>
<table>
  <tr><td>text1</td></tr>
  <tr><td>text2</td></tr>
  <tr><td>text3</td></tr>
  <tr><td>text4</td></tr>
</table>
<a href="">Previous</a>
</div>

Any help would be appreciated.


Solution

  • First, give ids to your elements:

    <a id="next" href="">Next</a>
    <table id="myTable">
        <tr><td>text1</td></tr>
        <tr><td>text2</td></tr>
        <tr><td>text3</td></tr>
        <tr><td>text4</td></tr>
    </table>
    <a id="prev" href="">Previous</a>
    

    Then, hide all elements except for the first one:

    $("#myTable tr").hide().eq(0).show();
    

    Finally, make the "Next" and "Previous" buttons toggle the visibility of the adjacent siblings, if exist:

    $("#next").click(function(e) {
        e.preventDefault();
        $("#myTable tr:visible").next().show().prev().hide(); // Will do nothing if the visible element is the last one
    });
    
    $("#prev").click(function(e) {
        e.preventDefault();
        $("#myTable tr:visible").prev().show().next().hide(); // Will do nothing if the visible element is the first one
    });