How to check if an html object exist

Let's say i have 1 to 4 dynamically generated checkboxes.  The checkboxes use the same name, and the number of checkboxes depend on some database values.  Now i want to add validation to these checkboxes.  I need to make sure at least one of them is checked, I'm thinking along these lines:

checkedFlag = 0
for (i=0;i<=3;i++)
{
   if (isObject(document.MyForm.MyChkBox[i]))  //how can i check if this is an object??
   {
        if (document.MyForm.MyChkBox[i].checked)
        {
           checkedFlag = 1
           break;
         }
    }
}
LVL 12
kingsfan76Asked:
Who is Participating?
 
archrajanConnect With a Mentor Commented:
if (isObject(document.MyForm.MyChkBox[i]))  //how can i check if this is an object??
shud be

 if (document.MyForm.MyChkBox[i])  
0
 
archrajanCommented:
For code to check if atleast one checkbox is checked
Here u go:
 <HTML>
<HEAD>
<SCRIPT LANGUAGE=javascript>
function atLeastOne(){
  var objForm = document.forms[0];
  var el = document.getElementsByName('frm_chk_delete[]')
  for(i=0;i<el.length;i++){
    if(el[i].checked){
       return true;
    }
  }
  alert("Please check at least one box!");
  return false;
}
</SCRIPT>
</HEAD>
<BODY>
<form name="frmYourForm" action="yourpage.htm" onSubmit="return atLeastOne()">
<INPUT type="checkbox" name="frm_chk_delete[]"><br>
<INPUT type="checkbox" name="frm_chk_delete[]"><br>
<INPUT type="checkbox" name="frm_chk_delete[]"><br>
<INPUT type="checkbox" name="frm_chk_delete[]"><br>
<INPUT type="submit" value="Submit" id=submit1 name=submit1>
</FORM>
</BODY>
</HTML>
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.