Showing or hiding controls using a client side script

This question might have ben asked number of times but my search did not yield a full answer to my question. I found some partial answers but I am sure a full well explained answer will satisfy me as a novice asp.net developer and people who are in the same boat as I am.

I like to use a checkbox and based on the selection of the checkbox, I want to show or hide number of controls (mainly labels and text boxes but possible to include other controls in the future). I want to do that at the client side to avoid round-trip delays (hence I believe I have to run a client side java script). My controls that I want to control their visibility using the checkbox also happened to be located close to each other and I can contain them in a DIV element if necessary.

I really appreciate a sample code to show how to implement such a thing in VS2005...

0
jsdude99
5/5/2008 12:40:11 AM
asp.net.web-forms 93655 articles. 6 followers. Follow

19 Replies
996 Views

Similar Articles

[PageSpeed] 3
Get it on Google Play
Get it on Apple App Store

In javascript you have hidden property per control to make them visible or invisible.


Cheers
Al
My Blog
MapStats.NET
Please click on 'Mark as Answer' if this post answered your question!
0
albertpascual
5/5/2008 2:05:01 AM

Thanks for the reply. Would you be kind enough to give an example? As I mentioned, I found similar comments but no detailed example to guide the novices...

0
jsdude99
5/5/2008 3:51:42 AM

jsdude99 :

Thanks for the reply. Would you be kind enough to give an example? As I mentioned, I found similar comments but no detailed example to guide the novices...

Here's an example

    document.getElementById('<%= TextBox1.ClientID %>').display = "none"; // TO HIDE
    document.getElementById('<%= TextBox1.ClientID %>').display = "block"; //TO SHOW


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
5/5/2008 3:55:33 AM

Hi,

you have to set attributes in the Page_load event in aspx.cs file as follow...

CheckBox1.Attributes.Add("onclick", "javascript:Check(this)");

 



in your aspx Page

add java script

 function Check(id)
        {
           
            var cb2 = document.getElementById("<%= CheckBox2.ClientID %>");
          

           if   (document.getElementById(id).checked == true)

            {

              cb2.display = "none";
 

            }

            else

            {

              cb2.display = "block";
 

            }  
 

}

 

int his example i have two checkbox (CheckBox1 and CheckBox2)

i have set attributes of CheckBox1 in aspx.cs field and set the onclick event of Checkbox

it calls function  Check(this).... here this means it pass CheckBox1 as parameter..

in JavaScript function..

i have taken client id of second CheckBox in variable cb2..

in condition i have checked that if first Checkbox is Checked then second CheckBox Should Not Display..

and if it is not checked than it should display..

 

if my post helps you ..

"Mark as Answer" 


Jigar Patel
Web Developer
India
0
Jigarpatel
5/5/2008 4:07:30 AM

Thanks Jigar for the most comprehensive answer so far. However, your solution did not work. When I click the first Checkbox, the browser shows "error on page" message and I do not know what is wrong. I then created a new web project and just put two check boxes and your code. Below are the contens of two files: 

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>

    <script type="text/javascript">

        function Check(id)
        {
           var cb2 = document.getElementById("<%= CheckBox2.ClientID %>");
           if   (document.getElementById(id).checked == true)
            {
              cb2.display = "none";
            }
            else
            {
              cb2.display = "block";
            }   
        }

    </script>

    <form id="form1" runat="server">
        <div>
            <asp:CheckBox ID="CheckBox1" runat="server" />
            <asp:CheckBox ID="CheckBox2" runat="server" />
        </div>
    </form>
</body>
</html>
  
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckBox1.Attributes.Add("onclick", "javascript:Check(this)");
        }
    }
}
 
0
jsdude99
5/5/2008 4:52:45 AM

 Hi,

        Just replace the javascript function with the below function

  function Check(id)
{
var cb2 = document.getElementById("<%= CheckBox2.ClientID %>");
if (document.getElementById(id).checked == true)
{
cb2.style.display = "none";
}
else
{
cb2.style.display = "block";
}

}


Hope this helps U... 


Regards,
Srinivas Ramanujan

Words offer the means to meaning, and for those who will listen, the enunciation of truth !!!!!
0
aresssrinivas
5/5/2008 4:58:42 AM

Still error on page message!!

0
jsdude99
5/5/2008 5:03:59 AM

 Hi,

i am sorry

i have made mistake here..

write

 

cb2.style.display = "none";
you have to add style in your statment cb2.display = "none"; 
 
still get error
replace 
var cb2 = document.getElementById("CheckBox2"); 
 
"Mark as Answer" 

Jigar Patel
Web Developer
India
0
Jigarpatel
5/5/2008 5:06:37 AM

I think aresssrinivas also picked "style" missing but neither his complete function replacement nor addding style got it working..

0
jsdude99
5/5/2008 5:11:23 AM

Hi,

write your error here...

 Have you replace

replace 
var cb2 = document.getElementById("CheckBox2"); 

 


Jigar Patel
Web Developer
India
0
Jigarpatel
5/5/2008 5:12:58 AM

Here's a working example for you..

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>

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

function toggleCheck()
{

     var cb1 = document.getElementById('<%= CheckBox1.ClientID %>')
     var cb2 = document.getElementById('<%= CheckBox2.ClientID %>')
        if (cb1.checked == true)
        {
            cb2.style.display = "none";
        }
        else
        {
            cb2.style.display = "block";
        }
   
    
}
</script>
</head>
<body runat="server">
    <form id="form1" runat="server">

         <asp:CheckBox ID="CheckBox1" runat="server" onclick="toggleCheck();" />
        <asp:CheckBox ID="CheckBox2" runat="server" />

    </form>
</body>

PS: I have tested on this and it works fine... :)
 


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
5/5/2008 5:15:53 AM

If I keep the first line below 

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

 (whic is generated automatically by VS2005 and have your entire code copy/pate it does not work. But if I get rid of that line, it now works. So, what makes the difference? I am still concerned though since they all are needed..

Also worthwile to note is that there is a warning in intellisense under onclick keyword on the line <asp:CheckBox ID="CheckBox1" runat="server" onclick="toggleCheck();" /> that "Attribute 'onclick' is not a valid attribute of element 'checkbox'

0
jsdude99
5/5/2008 5:31:15 AM

jsdude99:

Also worthwile to note is that there is a warning in intellisense under onclick keyword on the line <asp:CheckBox ID="CheckBox1" runat="server" onclick="toggleCheck();" /> that "Attribute 'onclick' is not a valid attribute of element 'checkbox'

Basically CheckBox has only onCheckChange event..But since we wanted to have an additional event attach to the checkbox then we added the javascript onclick event to make it work... Once it will render in the page then the javascript will recognize that event and execute the event...


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
5/5/2008 5:43:08 AM

Hi,

Actually onclick is javascript event..

and you write it to the server CheckBox control

thats why it is giving underline to it..actually it does not effect you.. its fine..

when actually you run that page..

if you see source of that page then  server checkbox seems as html checkbox input type control..

thats why its fine here..

i know that you will ask this question thats why i add attributes in the page load event and assign javascript over there ..

answer given by vinz is also true...

 

hope this post helps you to understand things..

 

 


Jigar Patel
Web Developer
India
0
Jigarpatel
5/5/2008 5:45:55 AM

Thanks to both of you for the explanation. The warning does not concern me now. But the problem is the removal of the first line. I tested by changing AutoEventWireup property to "false" while keeping the first line and got it working as well. Now my concern is changing a page directive which is automatically created by the environment and although I may get the javascript working but potentially screw-up other things and create further conflicts or compexity??

0
jsdude99
5/5/2008 5:55:18 AM

Hi,

at particular this peroperty, does not effect or conflict to you..

i dont think so..

and Please "Mark as Answer" to posts which helps you specially to help others to find right solutions...

thanks in advance 


Jigar Patel
Web Developer
India
0
Jigarpatel
5/5/2008 6:02:28 AM

jsdude99 :

I tested by changing AutoEventWireup property to "false" while keeping the first line and got it working as well. Now my concern is changing a page directive which is automatically created by the environment and although I may get the javascript working but potentially screw-up other things and create further conflicts or compexity??

Please read this article below

http://www.codeproject.com/KB/aspnet/AutoEventWireup.aspx

http://www.dotnetspider.com/resources/2630-About-Aut-ventWireup.aspx 

 


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
5/5/2008 6:06:13 AM

Hi

    I think you change the visible = false for the particular controls

    If the control visible is false in the form it does not identify the control to false the control visibility please using

    TextBox.Attributes.CssStyle.Add("visibility", "hidden"); 

    In the Page Load then you can Do it

    All the BestYes

Mark as ANSWER if the post is useful to you
    With Regards

    Solaimalai 


With Regards,
Solaimalai V.T
0
SolaimalaiVT
5/5/2008 6:48:26 AM

I finally get a working solution, without requiring to change AutoEventWireup propery (I believe the default state is different in VS2003&2005). This can be achieved by declaring the event in during page load as Jiger mentioned. I come-up with a working solution by combining both Jiger's and Vinz's posts. Thanks for your input and I mark both of you as correct answer. However, I at the end, I am not happy with the overall outcome since if you have text on the checkbox, only the checkbox disappears but the text stays. Also, the page shows both controls side by side when the page first loads but after hiding and showing, the checkboxes are shown on vertically staggered. Unless I find another way of doing it, I will ditch this idea and go back to server side to show/display it more aesthetically. Any way, below is the final working code with sticky text. I am providing that for helping out to the people like myself for future searches. 

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>

<script type="text/javascript" language="javascript">
function WorkingToggle()
{
     var cb1 = document.getElementById('<%= CheckBox1.ClientID %>')
     var cb2 = document.getElementById('<%= CheckBox2.ClientID %>')
        if (cb1.checked == true)
        {
            cb2.style.display = "none";
        }
        else
        {
            cb2.style.display = "block";
        }
}
</script>

<body>
    <form id="form1" runat="server">
        <div>
            <asp:CheckBox ID="CheckBox1" runat="server" Text="ABC" />
            <asp:CheckBox ID="CheckBox2" runat="server" Text="XYZ" />
        </div>
    </form>
</body>
</html>
  
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckBox1.Attributes.Add("onclick", "javascript:WorkingToggle();");
        }
    }
}
 
0
jsdude99
5/5/2008 7:09:08 AM
Reply:

Similar Artilces:

Hiding Group of Controls Using Client-Side Script
Hello Developers, I am trying to hide a group of controls enclosing them in a <div> element and altering its display property with client-side script. But, for any reason, it does not work and I just cannot figure out why. Any ideas? Complete example attached. Tomasz J<%@ Page Language="C#" %><%@ Register TagPrefix="ajaxToolkit" Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt...

How to access dynamically Html controls (client side controls) using C# server side scripts
Folks,I have problem try to to access dynamically Html controls (client side controls) using C# server side scripts. Please give me helps.     The error is as follows Exception Details: System.InvalidCastException: Specified cast is not valid.Source Error: Line 79: { Line 80: Control c = Page.FindControl("ddlTC" + i); Line 81: ((DropDownList)c).DataSource = mdt; Line 82: ((DropDownList)c).DataTextField = "ClassID"; Line 83: ((DropDownList)c).DataValueField = "Course"; My aspx page source codes: ...<...

How to access the properties and methods of the ActiveX control on the client side in Web Form using javascript or vbscript
Hi All, I have looked almost every where for this, and I'll be really appreciated if someone can help me with this. I found a article in MS KB article, #317392, but it is not extactly what I wanted. How do you reference an ActiveX control's methods and properties with javascript in the ASPX? Following is what I have. Some how the following line in the btnclick() does not seems to be working. AlarmCtl.StartTimer() I have done this with just .HTML and it works just fine. Can any one help. Thanks in advance. //===========================...

How to use client-side script(javascript) in DNA using .Net Remoting
Hi all,     It was known that SAO and Singleton object about .Net Remoting. When I Create an object in server side and hosting in IIS's virtual directory,I want to use javascript asynchronous invoking the remote object by HTTP channel, 80 port and SOAP formatter just like XMLHTTP invoking web service. My code as following, <script> objXmlDoc = new ActiveXObject("Msxml2.DOMDocument"); objHttp = new ActiveXObject("Msxml2.XMLHTTP"); strEnvelope = ?? objHttp.onreadystatechange = function() { ...... }   szUrl = "http://ServerNa...

Java script cannot differentiate client side controls in user control used multiple on same webform
I have a textbox with a automcomplete extender and a client side link that, when clicked, changes style.display from "none" to "" to display a div that contains a listview with all possible choices for the text box.  I am using javascript to change the div style.display when the link is clicked.  When I have two instances of the usercontrol on the same webform, both links display the div on the first control.  How can the client side javascript tell the difference between the two divs? Try putting the javascript of the user c...

Web Server Controls and Client-side scripting
Hi guys, I jus twant to ask something. While using Html server controls I can access the Web Form elements using Javascript :<script language=javascript>      alert(document.<formID>.elementName.value); //elementName is just the ID value of a control like txtName for a textbox control.</script> But using Web Server Controls I can not access the Web Form elements.When I type like alert(document.StepByStep1_2.txtName.Value) , txtName doesn't appear in the intellisence drop down menu but using Html server controls all the controls pl...

add client side script in web control
Hi, I want to open new window on click of Button server control. I create one .aspx page with web server contorls and validation controls. In aspx page following controls are there: (1)text box with regular expression control and required validation control. (2)text box with regular expression control and required validation control. (3)button control. I add java script in button control on the Page load event which is shown below: string features = "window.open(''textvalue.xls','new','height=320;width=160;left=100;top=50;location=no;menubar=no;...

Hide a control using client-side callbacks
Does anyone have an example of hiding a control using client-side callbacks? I have a fairly heavy page with lots of UpdatePanels, and even simple updates are taking a while to execute, so I'd like to start using client-side callbacks to speed things up. One of the most common things my app does is show/hide a textbox according to what option is selected in a dropdown (the dropdown is populated in the code-behind): <asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" /><asp:TextBox ID="txt" runat="server" Visible=&q...

web forms with client and server side controls??
Hi, I have a form that has client and server side controls. I have a problem in that any client controls (textbox) within the form runat="server" can not be accessed with client side code. Anyone got any ideas why and what work arounds are possible. Regards, Graham. once a form element is inside a <FORM> tag, you can no longer refer to it by its ID alone. you have to refer to it by formname.elementid or document.all.elementid. use document.getElementById(yourtextboxid) to get a ref to the element in the form. using this allows u to bypass the formn...

How to hide client script in web custom controls?
We know that a goog web custom control need lots of client script to support rich functions. But when I use some 3-party web custom controls, I can't find any scripts on the source codes in my web pages. normally, we need to include the script file in web pages. looks like: <script language="javascript" src="xxxxx.js"> or in server side, using RegisterClientScriptBlock to send client script to client side. But in this way, user can watch the script code. but what I found is just <script language="javascript src="controlnamepag...

how can use Client script in web user controle
 i need use method of clientScript in web uer control , but i dont know how? You can use javascripts in a web user controls just like u do in aspx pages except that you cannot hardcode the ids of controls in the javascript functions, Instead pass on the Client IDs like this function example(){   document.getElementById('<%=TextBox1.ClientID%>').value = 'test';} Also make sure that if more than one instance of the control is used in the page u need to handle the situation cleverly as the one which gets rendered in the last alone will work. Lemme know i...

Hiding rows in datagrid using client side script
Is it possible to hide rows in the datagrid at runtime using javascript? I am creating something similar to dual list box where you select rows in left listbox and move it to right. But I cannot use a list box because I have to show multiple columns. So I want to use datagrid, but am not sure if it is possible to hide rows using javascript. Thanks ...

Calling a client side script from web server control
I have an image button server control on a page, i need when i click on it to call the client side script which will add a new row to an HTML table on the same page. but it always ignore the script and nothing happen. any idea plz, thank u. here is the script am calling onclientclick with the image button<script type="text/jscript" language="javascript" > function addtoTable(){ var oRow = document.createElement("TR"); var oCell = document.createElement("TD");var CONT1 = document.createTextNode("TEST"); oCell.appendChild(CONT...

How to use client-side script(javascript) in .Net Remoting
Hi all,     It was known that SAO and Singleton object about .Net Remoting. When I Create an object in server side and hosting in IIS's virtual directory,I want to use javascript asynchronous invoking the remote object by HTTP channel, 80 port and SOAP formatter just like XMLHTTP invoking web service. My code as following, <script>  objXmlDoc = new ActiveXObject("Msxml2.DOMDocument"); objHttp = new ActiveXObject("Msxml2.XMLHTTP"); strEnvelope = ?? objHttp.onreadystatechange = function() { ......  }    szUrl = &...

Web resources about - Showing or hiding controls using a client side script - asp.net.web-forms

Control - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Gun control: Barack Obama plans to bypass senate, push through executive action on gun control
Barack Obama will meet with Attorney-General Loretta Lynch to discuss ways of reducing gun violence through measures that do not require congressional ...

Obama to Explore Bypassing Congress Gun Control - Al Jazeera America
'We know that we can't stop every act of violence,' Obama said Friday. 'But what if we tried to stop even one?'

Obama to impose gun control curbs
CBS News Obama to impose gun control curbs Ames Tribune HONOLULU — President Obama will press ahead with a set of executive actions on guns ...

Demographics Could Kill The GOP Off But Not In Congress, Not While Pelosi Controls The DCCC
... Democratic voters. In November 2014, Republican voters did just that with dramatic congressional victories that allowed the GOP to take control ...

Obama Touts First Seven Years, Pledges to ‘Move Forward on Our Unfinished Business’ on Gun Control
Obama Rips Congress, Pledges to 'Move Forward on Our Unfinished Business' on Gun Control

Republicans fire back at Obama's gun control move
CBS News Republicans fire back at Obama's gun control move CBS News January 2, 2016, 6:31 PM - When President Obama returns from his Hawaiian ...

Obama plans to outflank hostile Congress with unilateral gun control moves
Obama said yesterday he has received &quot;too many letters from parents, and teachers, and kids, to sit around and do nothing&quot;.

Trump blasts Obama's planned actions on gun control
CNN Trump blasts Obama's planned actions on gun control CNN Washington (CNN) Donald Trump is denouncing President Barack Obama's plan to expand ...

Obama to try executive action on gun control in end-run around Congress
The president is meeting with the US attorney general next week; sources indicate he will use executive orders to tighten background checks. ...

Resources last updated: 1/3/2016 10:43:06 AM