Show/Hide Panel via javascript in Asp.Net

It is very simple to hide an element with javascript.  In this example we will use a panel as the element to show/hide.

First we must include the script to do the work we will call it showHide.  You can do this in the html or register it via the ScriptManager.  This function is not limited to panels.

<script language="javascript" type="text/javascript">
   function showHide(id)
   {
       var el = document.getElementById(id);
       if(el.style.display == 'none')
       {
           el.style.display = 'block';
       }
       else
       {
           el.style.display = 'none';
       }
   }

    </script>

Next we can use an object to trigger the script.  We will do a hyperlink and a button.  Inside the form put:

<input type="button" onclick="showHide('<%=Panel1.ClientID%>');" 
value="Show/Hide"><a href="#" onclick="showHide('<%=Panel1.ClientID%>');
">Show/Hide</a> <asp:Panel ID="Panel1" runat="server">Panel to Show/Hide
</asp:Panel>

Here we used Panel1.ClientID in the showHide method on the onlick event incase you have a masterpage.  If you have a masterpage, the controls inside the contentplaceholders are renamed.  For the link we put # because we do not want to to actually post anywhere.

Demo

 

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Posted by: kjsteuer
Posted on: 5/7/2008 at 4:11 PM
Tags: ,
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (57) | Post RSSRSS comment feed