Tuesday, January 10, 2012

How to Visible/Hide the controls using JavaScript in ASP.Net


There are two ways we can make the control to hide/visible.
First
 
1    JavaScript
<script language="javascript" type="text/javascript">

function hide() {
        if (document.getElementById('<%= DropDownList1.ClientID %>').value == "Button") {
            document.getElementById('<%= Button.ClientID %>').style.visibility = "visible";
            document.getElementById('<%= TextBox.ClientID %>').style.visibility = "hidden";
        }
        else {
            document.getElementById('<%= Button.ClientID %>').style.visibility = "hidden";
            document.getElementById('<%= TextBox.ClientID %>').style.visibility = "visible";
        }
    }

</script>

Aspx
<asp:DropDownList ID="DropDownList1" runat="server" onchange="hide();return false">
        <asp:ListItem>Button</asp:ListItem>
        <asp:ListItem>Textbox</asp:ListItem>
        </asp:DropDownList>
        <br />
        <asp:Button ID="Button" runat="server"  Text="Button" />
        <asp:TextBox ID="TextBox" runat="server" ></asp:TextBox>

Second

2    JavaScript
<script language="javascript" type="text/javascript">

function hide2() {
        if (document.getElementById('<%= DropDownList2.ClientID %>').value == "Button") {
            document.getElementById('<%= Button1.ClientID %>').style.display = "block";
            document.getElementById('<%= TextBox1.ClientID %>').style.display = "none";
        }
        else {
            document.getElementById('<%= Button1.ClientID %>').style.display = "none";
            document.getElementById('<%= TextBox1.ClientID %>').style.display = "block";
        }
    }
</script>

Aspx
<asp:DropDownList ID="DropDownList2" runat="server" onchange="hide2();return false">
        <asp:ListItem>Button</asp:ListItem>
        <asp:ListItem>Textbox</asp:ListItem>
        </asp:DropDownList>
        <br />
        <asp:Button ID="Button1" runat="server"  Text="Button" />
        <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>

If you want to hide control by default use second approach by adding style="display:none"
Attribute
<asp:Button ID="Button1" runat="server" style="display:none"  Text="Button" />
<asp:TextBox ID="TextBox1" runat="server" style="display:none"  ></asp:TextBox>

I hope this article will be very helpful to all. Thanks for reading this article.

“Keep reading and share the knowledge”  
“Grow more trees to save Earth”

1 comment:

  1. Hi,

    This is srinivas. I am a student learning asp.net. I am trying to create a feedback form in thich i have a doubt.

    I have a hidden textbox


    Now using javascript i want to show that hidden textbox on pressing a button. I am unbale to do so. can u please help me

    regards

    Srinivas
    9949040586
    srinivaspolishetty@gmail.com

    ReplyDelete