adsense

Thursday, May 4, 2017

Expand and Collapse a html Table Rows on Click

HTML Table rows can be easily expanded/collapsed using jQuery as displayed in  code snippet below.

e.g.
HTML

<table class="Menu">
            <tr class="row" >
               <td>Menu 1</td>
            </tr>
            <tr class="row" >
                <td>
                    Sub Menu 1
                    Sub Menu 2
                </td>              
            </tr>
            <tr class="row" >
                <td>Menu 2</td>
            </tr>
        </table>

JavaScript

<script type="text/javascript">
           $(function(){
              //collapse all rows on load
              $(".row").hide();
              
              ToggleCollapse();
           });

  function   ToggleCollapse(){
    var isCollapsed = true;

    $(".Menu").click(function () {
                    if (isCollapsed) {
                        $(".row").show();
                        isCollapsed = false;
                    }
                    else
                    {
                        $(".row").hide();
                       isCollapsed = true;
                    }
                  });
 }
</script>


I have used CSS classes to identify the table rows and  the HTML Table.

Cheers,
Samitha

No comments:

Post a Comment