Javascript - Not Selecting All Checkboxes

Hi Guys,

I’m using Javascript to make all the checkboxes checked in a form, but when i click the button to check them all it will only select the first checkbox. Why is this?

JAVASCRIPT:


	function checkUncheckAll(theElement) {
     var theForm = theElement.form, z = 0;
	 for(z=0; z<theForm.length;z++){
      if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
	  theForm[z].checked = theElement.checked;
	  }
     }
    }

CODE:


<input name="checkall" onclick="checkUncheckAll(this);" type="checkbox" />
  </tr>
<tr class="tabletext">
<?php
$i=0;
while ($i < $num) {
$LeadID=mysql_result($result,$i,"LeadID");
$ProgramID=mysql_result($result,$i,"ProgramID");
$ProgramName=mysql_result($result,$i,"ProgramName");
$AffID=mysql_result($result,$i,"AffID");
$AdID=mysql_result($result,$i,"AdID");
$Status=mysql_result($result,$i,"Status");
$Payout=mysql_result($result,$i,"Payout");
?>
<tr>
<td class="tableresultstxt"><? echo $LeadID; ?></td>
<td class="tableresultstxt"><? echo $ProgramID; ?></td>
<td class="tableresultstxt"><? echo $ProgramName; ?></td>
<td class="tableresultstxt"><? echo $AffID; ?></td>
<td class="tableresultstxt"><? echo $AdID; ?></td>
<td class="tableresultstxt"><? echo $Status; ?></td>
<td class="tableresultstxt"><? echo $Payout; ?></td>
<td>
  <p>
    <input type="checkbox" name="theForm" id="<? echo $id; ?>" value="<? echo $id; ?>">
  </p>
</form></td>
</tr>
<?
$i++;
}
mysql_close();
?>

</table>


Any help would be great please.

Thanks.

 var theForm = theElement.form

This isn’t referencing the form, or any elements inside of it.

To reference all the checkboxes in this scenario, you could use document.getElementsByName():

 var theForm = document.getElementsByName("theForm")

hopefully this function will help

<script type="text/javascript">

function checkUncheckAll(obj) {
    var chkboxesO = document.getElementsByName('theForm'); //get checkboxes to check/uncheck
    for(i=0; i < chkboxesO.length; i++){
    	chkboxesO[i].checked = obj.checked;
    }
}

</script>

Thanks guys, works now :slight_smile:

Thumbs Up!