Search code examples
javascriptasp.net

How to get checkbox1.Checked property within a javascript?


I have two checkboxes. When I checked both checkboxes, I want to generate an alert "Passed". I have written like this

<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
<title>Untitled Page</title> 
 
  <script type="text/javascript" >
   function validate() {
    if (document.getElementById('CheckBox1').checked &&   document.getElementById('CheckBox2').checked) {

        alert("passed");

     } else {
        alert("Referred")
    }
}
</script>


   <asp:CheckBox ID="CheckBox1" runat="server"  OnCheckedChanged="javascript:validate();" />
   <asp:CheckBox ID="CheckBox2" runat="server"  OnCheckedChanged="javascript:validate();" />

but the problem is this (checkbox1).checked is not getting inbuildly within the . how can I get it? is there any need for adding extra properties to my project for getting the .checked property? it's first time I'm using javascript. and my visualstudio version is 3.5.please help


Solution

  • OnCheckedChanged is a server side event, and you are handing it on the client side.

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

    Also you might need to use .ClientID -

    (document.getElementById('<%=CheckBox1.ClientID%>').checked &&   document.getElementById('<%=CheckBox2.ClientID%>').checked)