asp:checkbox hide/show text/fields when it's clicked without doing a postback?

U

UJ

Is there a way with a asp:checkbox to run a JavaScript to display/hide
text/input on the screen without doing a postback?

I also need to be able to access the stuff at the server so I need to have
run=server with it.

TIA - Jeff.
 
G

Greg Young [MVP]

Yes you can add javascript to the control.

in your code behind you can do this through ...

Checkbox.Attributes.Add("onclick", "yourjavascriptfunction(this)")
 
O

Onwuka Emeka

Yes there are ways to do that. the asp:checkbox ultimately renders a an
<input type='checkbox'> html tag to the web browser .
if it were a html control you can do this by adding an onclick attibute to
the tag i.e. <input type='checkbox' onclick='someJavaScript();'> right?
you can also do that with an asp:CheckBox control by adding the attribute
key, value pair to the Attributes collection of the control thus:
CheckBox.Attributes.Add("attributename","attributevalue") .

copy, save and host the code below. The trick is in the OnInit method where
the onClick attribute of the checkbox is added.

<%@ Page language="c#" AutoEventWireup="false" %>
<HTML>
<HEAD>
<title>Javascript Show Hide</title>

<script language=javascript>
function showHide(checkbox,textboxId)
{
var textbox = document.getElementById(textboxId);
if(checkbox.checked)
{
textbox.style.display = '';
}
else
{
textbox.style.display = 'none';
}
}
</script>
<script language=C# runat=server>
override protected void OnInit(EventArgs e)
{
chbShowHide.Attributes.Add("onClick",string.Format("javascript:showHide(this,'{0}');",txtShowHide.ClientID));
base.OnInit(e);
}
</script>
</HEAD>
<body >
<form id="frmShowHide" method="post" runat="server">
<asp:TextBox id="txtShowHide"
runat="server"></asp:TextBox>
<asp:CheckBox id="chbShowHide" Checked=True
runat="server"></asp:CheckBox>
</form>
</body>
</HTML>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top