简体   繁体   中英

how to select/deselect all checkboxes generated in loop when parent checkbox is checked

<script>
    $(function(){
    $('.parent').on('click',function(){
    $(this).find('.child[]').attr('checked',this.checked);
    });
});
</script>
<table>
  <thead>
    <tr>
      <th>S No.</th>
      <th><input type="checkbox" name="select1" id="select1" class="parent" /></th>
      <th>Title</th>
      <th>End Date</th>
      <th>Action</th>
      <th>Deal Type</th>
      <th>Status</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
    <?php $sql="select * from table_name where id='$id'";
      $result=mysql_query($sql); 
      $sn=1;
      while($show=mysql_fetch_array($result))
      { 
          $student=$show['student'];

      ?>
      <td><?php  echo $sn; ?></td>
      <td><?php echo "<input type='checkbox' name='check[]' class='child[]' id='check[]' value='".$student."'/>"; ?></td>
      <td>enddate</td>
      <td>View</td>
      <td>Edit</td>                                            
      <td>Delete</td>
      <td>xyz</td>
    </tr>
    <?php $sn++ }}?>

Here, checkbox-name=select1 is out of loop and it is parent checkbox. checkbox-name=check is actually an array of checkbox coming along with data from database. If there are 10 entries in database, 10 checkboxes will come. I want that if I check parent checkbox, then all checkboxes should get checked irrespective of numbers you can say, just like gmail. Also please tell where to place javascript/jquery. Thank you for your answers.

The this inside your click callback would refer to the checkbox itself. So $(this).find('.child[]') will not find any elements.

Also note that the class="index[]" will not work with jQuery, so you would like to change that to class="index" . You can leave name="index[]" as it is.

If you want to look for elements inside the scope of the parent table (thus allowing you to have multiple structures of (un)check all), you would use:

$(function(){
  $('.parent').on('click',function(){
      $(this).parents('table').find('.child').attr('checked',this.checked);
  });
});

If you want to look for just all child nodes in the document, you would use:

$(function(){
  $('.parent').on('click',function(){
      $('.child').attr('checked',this.checked);
  });
});

Kind regards,

Arnoud

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM