How to get checkbox text in javascript?

K

Kb

Hi all,
I have an asp:checkbox on a form, and i added onclick attribute to it. When
the checkbox is clicked I want to add its text to a textbox. But I can't get
its text. The checkbox is rendered in html separately, followed by the
<label for> tag - that's where the text is. But how to access it?

Any help is appreciated.
 
K

Ken Cox [Microsoft MVP]

Ok, this is a total hack, but I'm assuming want to desperately avoid a
postback. You can use script to check if the checkbox is checked, get at the
innertext of the Label with some Javascript and stuff it into the textbox.
Here's a sample that might get you started:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>chbxfrm</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
<script language=javascript>
function elemnts() {
for(i = 0; i < document.all.length; i++){
if (document.all("chkRed").checked==true) {
if (document.all(i).tagName=="LABEL") {
document.all("TextBox1").value=document.all(i).innerText
break;
}
}
}
}
</script>
</HEAD>
<body MS_POSITIONING="FlowLayout">
<form id="Form1" method="post" runat="server">
<P>
<asp:CheckBox id="chkRed" runat="server"
Text="Red"></asp:CheckBox>&nbsp;</P>
<P>
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox></P>
<P>
<asp:Button id="Button1" runat="server" Text="OK" ></asp:Button></P>
</form>
</body>
</HTML>


Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Attributes.Add("onclick", "elemnts();")
End Sub

Ken
MVP [ASP.NET]
Toronto
 

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

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top