Expandable table view in HTML

3k Views Asked by At

I am building a dynamic table that fetches and displays data from database, the structure of table looks like this

<table class="table" id="report">
  <thead>
    <tr>
      <th>Title</th>
      <th>Skill</th>
      <th>Area</th>
    </tr>
  </thead>

  <tbody>
    <?
      $sql="SELECT * from tablename ";
      $result= mysqli_query($con, $sql);
      if(mysqli_num_rows($result)>0) {
        while($row = mysqli_fetch_assoc($result)) {
          <tr>
            <td><? echo $title; ?></td>
            <td><? echo $skill; ?></td>
            <td><? echo $area; ?></td>
          </tr>
        }
      }
  </tbody>
</table>

I wish that when a user clicks on title a view should expand and then on another click it should collapse.

I built a static table in jsfiddle and it was working fine, but when I tried to merge the code with my above table it is not working. Can anyone please tell where I went wrong?

1

There are 1 best solutions below

4
On

Try this JS Fiddle and hopefully it'll work, I added the dummy text inside that td and on click on the td that toggles the visibility of child div .hidden

$(document).ready(function () {
    $('.expandable').on('click', function(){
     $(this).children('.hidden').toggle();
    });
});
.hidden {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="report" border="1" style="width:100%" >
    <tr>
        <th> First </th>
        <th> Second </th>
        <th> Third </th>
    </tr>

    <tr>
         <td class="expandable">1st title
            <div class="hidden">dummy text 1
                <br>dummy text 1
                <br>dummy text 1
                <br>
            </div>
        </td>
         <td>1</td>
         <td>1</td>
    </tr> 
    <tr>
         <td class="expandable">2st title
            <div class="hidden">dummy text 2
                <br>dummy text 2
                <br>dummy text 2
                <br>
            </div>
        </td>
         <td>2</td>
         <td>2</td>
    </tr>
</table>