Search code examples
phpjqueryshow-hide

How to show/hide specific table rows using jQuery


I'm displaying some data in a table and for each row I have another one with some details that is hidden by default and I want to make it visible only when the user clicks a link.

HTML looks like this:

<div id="listing">
    <?php for(): ?>
        <tr>
            <td><a href="#" class="toggle">Toggle</a></td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
        </tr>
        <tr class="details" style="display: none">
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>...</td>
        </tr>   
    <?php endfor; ?>
</div>

I tried using jQuery like so, but with no results:

$('#listing').on('click', '.toggle', function(e) {
    e.preventDefault();
    $(this).closest('tr .details').toggle();
});

Solution

  • On each first row element provide it a data-target this will be which class to target and toggle the show/hide.

    So basically on click for toggle class we get the data-target use that value to find our target and then simply toggle the target.

    JsFiddle : https://jsfiddle.net/63ujphmj/

    Javascript

    $(function()
    {
        $('.toggle').on('click', function()
      {
        var target = $(this).data('target');
        $('.'+target).toggle();
      });
    });
    

    Html

    <div id="listing">
      <table>
        <tr>
          <td><a href="#" class="toggle" data-target="details-1">Toggle 1</a></td>
          <td><a href="#" class="toggle" data-target="details-2">Toggle 2</a></td>
          <td><a href="#" class="toggle" data-target="details-3">Toggle 3</a></td>
          <td><a href="#" class="toggle" data-target="details-4">Toggle 4</a></td>
        </tr>
        <tr class="details">
          <td class="details-1" style="display: none">Toggle 1 details</td>
          <td class="details-2" style="display: none">Toggle 2 details</td>
          <td class="details-3" style="display: none">Toggle 3 details</td>
          <td class="details-4" style="display: none">Toggle 4 details</td>
        </tr>
      </table>
    </div>