I want that when i check or uncheck the checkbox state,accordingly in label text is changed.
If i check the checkbox,then in label text is checked else unchecked.

protected void Page_Load(object sender, EventArgs e)
    {
        CheckBox1.Attributes.Add("oncheckedchanged", "javascript: return CheckboxState");
    }


<script language ="javascript" type ="text/javascript"> 
 function CheckboxState()
 {
 var checkbox=document.getElementById("CheckBox1");
 var lbl=document.getElementById ("Label1");
 alert(checkbox.checked);
 lbl.innertext=checkbox.checked;
 return false;
 }
 
</script>

But when i check or uncheck,firstly page is postbacked & secondly,in label nothing is coming..

Recommended Answers

All 3 Replies

OnCheckedChanged is a server side event. You are calling a javascript function for a server side event whichi is wrong.
Use onchange event which is a client side event.

Change your code as below

protected void Page_Load(object sender, EventArgs e)
    {
        CheckBox1.Attributes.Add("onchange", "javascript: return CheckboxState()");
    }

Its not working,I have written alert in JS function,but that alert is also not popping up.means JS function is not called...

protected void Page_Load(object sender, EventArgs e)
    {
        CheckBox1.Attributes.Add("onchange", "javascript: return CheckboxState()");

    }
script language ="javascript" type ="text/javascript"> 
 function CheckboxState()
 {
 var checkbox=document.getElementById("CheckBox1");
 var lbl=document.getElementById ("Label1");
 alert(checkbox.checked);
 lbl.value=checkbox.checked;
 return false;
 }
 
</script>

Use InputAttributes instead of Attributes with CheckBox control.

protected void Page_Load(object sender, EventArgs e)
    {
        CheckBox1.InputAttributes.Add("onchange", "return CheckboxState()");
    }

Also use innerText to assign value to label control instead of value property.

<script language ="javascript" type ="text/javascript"> 		function CheckboxState() {
			var checkbox = document.getElementById("CheckBox1");
			var lbl = document.getElementById("Label1");
			alert(checkbox.checked);
			lbl.innerText = checkbox.checked;
			return false;
		}

	</script>

Please note that the onchange will fire only if you move focus to other control from checkbox.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.