Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking dynamic checkboxes -- first checkbox checked 1

Status
Not open for further replies.

TeaAddictedGeek

Programmer
Apr 23, 1999
271
US
How does one check if a checkbox is checked if you don't necessarily know the name or ID of the checkbox (dynamically created). Say you want to make sure the first checkbox in the form is checked before submitting the form. Is this possible?

"The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs."
-Joseph Weizenbaum
 
Use the getElementsByTagName collection to grab all inputs and then check to make sure the type is checkbox. Here's an example:
Code:
<html>
<head>
<script type="text/javascript">

function createCheckbox() {
   document.getElementById("theDiv").innerHTML = "<input type=\"checkbox\" />checkbox1<br /><input type=\"checkbox\" />checkbox2";
}

function validateMe(frm) {
   [!]chks = document.getElementsByTagName("input");[/!]
   var i = 0;
   for (i = 0; i < chks.length; i++) {
      //check to see if we found the FIRST checkbox
      [!]if (chks[i].type = "checkbox") {[/!]
         //check to see if the first checkbox was checked
         if (chks[i].checked) {
            alert("first checkbox on the form was checked, submission proceeding");
            return true;
         }
         else {
            alert("the first checkbox on the form must be checked when submitting");
            return false;
         }
      }
   }
   alert("no checkboxes found");
   return false;
}

</script>
</head>

<body onload="createCheckbox()">
   <form onsubmit="return validateMe(this)" method="get" action="">
      <div id="theDiv"></div>
      <input type="submit" value="submit me" />
   </form>
</body>
</html>

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
omg, haven't done that in years......

this:
Code:
if (chks[i].type = "checkbox") {

should be:
Code:
if (chks[i].type [!]==[/!] "checkbox") {

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Thanks a million! It works. :)

"The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs."
-Joseph Weizenbaum
 
no problem [thumbsup2]

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top