Tuesday, April 5, 2011

ASP.net hiding panel using javascript

Hi,

I have a radioButtonList with 2 items in it. A radiobutton with a "Yes" value and a radionButton with a "No" value.

Below that I have a panel which I want made visible when "Yes" radioButton is selected and hidden when "No" is selected. I had originally implemented this using the AutoPostBack attribute but I want to do it in Javascript so that it doesn't cause a postback. Here's the code. Any help would be greatly appreciated.

<asp:RadioButtonList ID="rbl1" runat="server" onClick="changed(this);" >
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>

<asp:Panel ID="panel1" runat="server">
<--other controls here -->
</asp:Panel>

function changed(rbl) {
        //not sure what to put in here
    }

Thanks in advance,

Zaps

From stackoverflow
  • If you add a class or determine the real id of "panel1", you can use jQuery to hide it easily:

    $('idOfPanel').hide();
    

    Or you without using jQuery, using the id of the div/panel:

    idOfPanel.style.display = "none";
    

    To redisplay:

    $('idOfPanel').show();
    

    Or

    idOfPanel.style.display = "block";
    
  • Here is a quick example I made up:

    <!-- Used grouped radio buttons instead of the RadioButtonList as it is harder to deal with -->
    <asp:RadioButton ID="rbYes" runat="server" Text="Yes" GroupName="YourGroupName" Checked="true" />
    <asp:RadioButton ID="rbNo" runat="server" Text="No" GroupName="YourGroupName" />        
    <br /><br />    
    <!-- Use a div instead of a panel.  Panels are just glorified divs. -->
    <div id="divTest">
        This is a test
    </div>
    
    <script type="text/javascript">
        $(document).ready(function()
        {
            $('#<%= rbYes.ClientID %>').click(function() { $('#divTest').show(); });
            $('#<%= rbNo.ClientID %>').click(function() { $('#divTest').hide(); });
    
        });
    </script>
    
  • try this:

    if (this.value == "No")
    {
    document.getElementByID('<%=panel1.ClientId%').style.display = "none";
    }
    else
    {
    document.getElementByID('<%=panel1.ClientId%').style.display = "block";
    }
    

    Hope it helps.

  • if you don't mind doing a partial postback, you can also throw your code into an UpdatePanel (assuming that you don't want to postback so that the entire page doesn't have to go through a page life-cycle)

0 comments:

Post a Comment