Introduction
One of the functional requirements for my web page is to hide an ASP.NET Label Control after displaying it for number of seconds in response to button click event. I found few examples on Google.com but somewhat not meet my constraint. I'm also looking for functionality to hide controls other than the Label control, hide multiple controls simultaneously and writing client-side JavaScript for re-use. I have put together an example code showing the implementation of the mentioned requirements.
Figure 1
Putting everything together
Shown below is the JavaScript function that accepts two parameters namely ctrl and timer. The first parameter is a string that contains the control ID for HTML markup. We can pass in a single control ID or as many control ID as we need from the code behind. See below for an example.
1. ControlOne.ClientID
2. ControlOne.ClientID + ","+ControlTwo.ClientID +", " + ControlThree.ClientID + …
The second parameter indicates how many milliseconds from now the application
should hide the control. This client-side script split the ctrl on
the comma (,) and put the results into an array. Then it will loop through the
array and set the element property display value to "none".
function HideCtrl(ctrl, timer) {
var
ctry_array = ctrl.split(",");
var num =
0, arr_length = ctry_array.length;
while (num
< arr_length) {
if
(document.getElementById(ctry_array[num])) {
setTimeout('document.getElementById("'
+ ctry_array[num] + '").style.display =
"none";', timer);
}
num += 1;
}
return false;
}
Shown in listing 2 is the content of the .aspx file.
Listing 2<div style="width: 90%;">
<div style="background:#CCCFFF;padding:5px 0 6px 10px">Guess the number game</div>
<div style="border:solid 1px #919191;padding:0 0 20px;min-height:100px;">
<asp:Label ID="Label1" runat="server" Text="Enter a number between 1 and 5"></asp:Label>
<asp:TextBox ID="txtAns" runat="server" Width="30px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ErrorMessage="*" Display="Dynamic" ControlToValidate="txtAns" />
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="(1-5)"
ControlToValidate="txtAns" Display="Dynamic" MaximumValue="5" Type="Integer"
MinimumValue="1"></asp:RangeValidator>

Join the conversation! Your thoughts help the community grow.