Pages

Friday, October 28, 2011

Show Hide HTML Contents inside Nested Loops

Show hide contents with Javascript is not a big issue in php, HTML development. But when it comes to dynamically changing environment, contents inside a loop which the number of rows not known, it gets little difficult. Because Javascripts are running on client side and it will do the job through content IDs. Below code will show you how to show/hide contents inside a loop where the number of rows not predefined and also the number of rows inside a single row also not predefined. Basically a nested loop.

This is the Javascript code inside the <head>

<script type="text/javascript">
function toggle(div_id, count)
{
    for (i=0;i<=count;i++)
    {
        var a=div_id+"-"+i;
        var divval = document.getElementById(a);
        if (divval != null)
        {
            if ( divval.style.display == 'none' )
            {   
                divval.style.display = 'block';
            }
            else
            {
                divval.style.display = 'none';
            }
        }
    }

</script>

And here is the php,

$count = 0;
while(condition for loop1)
    {
            $count2 = 0;
            while(condition for loop2)
            {
                       ?>
                       
                        <tr  id='<? echo $count."-".$count2 ?>' style="display:none"><td></td></tr>                       
                        <?
                         $count2 = $count2+1;
              }
              $count = $count+1;
              ?>
             <tr id='<? echo $count."-more" ?>' style="display:block"; align="right"><td><img src="./images/more.png" align="right" onmouseover="this.src='./images/moremo.png';" onmouseout="this.src='./images/more.png';" onclick="toggle('<? echo $count ?>', '<? echo $count2 ?>')" height="17" width="40"  /></td><td>&nbsp;</td></tr>
             <?
     }

The basic idea of this code is a 'show more records' button inside the first loop. (one button per record) According to the button click event it will show/hide the result of the second loop.
What I have done here is sending the div_id (count of the first loop) and the number of records in the second loop to the JScript. The JScript will run another loop for the count of the second mentioned loop and do the necessary. See how I have created dynamic div ids.

Simple but powerful JavaScripts
Regards,