checkbox validation with javascript

why does this not work?

<script type="text/javascript">
function validateCheckbox() {
 if(!document.form1.CheckBoxESA.checked){
    alert("required");
   return false;
  }
   return true;
 }
</script>


<form id="form1" runat="server" onSubmit="return validateCheckbox();">
<table cellpadding="0" cellspacing="0" border="0">
 <tr>
   <td>
      <asp:CheckBox id="CheckBoxESA" runat="server" TextAlign="Left" Text="I agree to the terms">
      </asp:CheckBox>
   </td>
 </tr>
 <tr>
   <td colspan="2" align="center">
     <input type="submit" name="submit" value="Submit">
   </td>
 </tr>
</table>
</form>
fwstealAsked:
Who is Participating?
 
DBAduck - Ben MillerPrincipal ConsultantCommented:
Because a Server side object may change it's name when it renders to the browser to avoid naming conflicts.  So in your code it will be named CheckBoxESA and if you viewed the source of your web page, it may be ctrl0_CheckBoxESA.

So when you do that you will want to make sure that you render

<script type="text/javascript">
function validateCheckbox() {
 if(!document.form1.<%= CheckBoxESA.ClientID %>.checked){
    alert("required");
   return false;
  }
   return true;
 }
</script>

This will send out the name of the object that will be rendered and not just what you expect to be rendered.
But I would use the getElementById( ) instead of just going by form1.

Ben.
0
 
gordonkennedyCommented:
I don't think you can access asp elements from within a client script.

Try having your checkbox as an html item instead :
<INPUT type=checkbox id=CheckBoxESA>I agree to the terms<P>

Then reference this in your client script using :
if (!document.getElementById('CheckBoxESA').checked) {

Hope this helps.
0
 
fwstealAuthor Commented:
this is what i did in asp.net 2.0 c#:

<script type="text/javascript">
function validateCheckbox() {
 if(!document.form1.<%= CheckBoxESA.ClientID %>.checked){
    alert("The ESA is required.");
   return false;
  }
   return true;
 }
</script>

<asp:Button id="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" OnClientClick="return validateCheckbox();"></asp:Button>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.