Link to home
Create AccountLog in
Avatar of PaulSWT
PaulSWTFlag for United States of America

asked on

Check all checkboxes with dynamic checkboxes PHP JavaScript

I am trying to get a JavaScript function to check all checkboxes in my form.  The problem I am having is that my form generates the checkboxes dynamically.  I am attaching the snippets of code, if anyone has the solution for this I would appreciate it!

I was able to get all this work by making the dynamic checkboxes static (taking off the brackets []).

Thanks,
Paul
// JavaScript
<script language="javascript" type="text/javascript">
  function checkAll(chk) {
    for (i = 0; i < chk.length; i++)
    chk[i].checked = true ;
  }
</script>
 
 
// Dynamic Checkboxes
<?php
while ($res->fetchInto($row)) {
  <input type='checkbox' name='bill[]' value='$orderID$orderGenerationID'>
}
?>
 
 
// Call JavaScript function
<input type='checkbox' onClick='checkAll(document.billSelected.bill)'>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of PaulSWT

ASKER

Thank you!
Avatar of aconrad
aconrad

document.billSelected.bill  <-- this doesnt exist,  the name is bill[]
below also words.tested
// JavaScript
<script language="javascript" type="text/javascript">
  function checkAll() 
  {
    var setto = false;
    if (document.forms['frm'].elements['check_all'].checked)
    {
      setto=true; 
    }
    
    chk = document.forms['frm'].elements['bill[]'];
    for (i = 0; i < chk.length; i++)
    {
      chk[i].checked = setto ;
    }
  }
</script>
 
<form name="frm">
// Dynamic Checkboxes
<?php
foreach (range(1,10) as $nr) {
  ?><input type='checkbox' name='bill[]' value='<?=$nr?>'><?
}
?>
 
 
// Call JavaScript function
<input type='checkbox' name="check_all" onClick='checkAll();'>
 
</form>

Open in new window