简体   繁体   中英

Toggle multiple checkboxes, but not all on select

In an existing project, a table is filled with a checkbox and a description in each row. headlines followed by several rows of the same group which should be toggled pon checking the headline:

for($i = 1; $i < count($inhaltIDList); $i++)
{
    echo '<tr><td><input type="checkbox" disabled name="1" value="">
        </td>'."\n";
    echo "<td><strong>Description"</strong></td></tr>\n";

    for($x = 0; $x < count($inhalt); $x++)
    {
        echo '<tr><td><input type="checkbox"  name="absatz[]"         value="'.$inhaltIDList[$i].','.$absatzbuchstaben[$x].'" '.$check.'>        </td>'."\n";
        echo '<td>'.$inhalt[$x].'</td></tr>'."\n";
        $check = '';
    }
}

How to toggle all checkboxes from the second for-loop upon selecting the one from the first loop?

What you need to do is give the check boxes from the first loop ID's and all the check boxes in the second loop classnames unique to the first box. What you end up with is something like this:

for($i = 1; $i < count($inhaltIDList); $i++)
{
    echo '<tr><td><input type="checkbox" disabled name="1" value="" id="allBox'.$i.'">
        </td>'."\n";
    echo "<td><strong>Description"</strong></td></tr>\n";

    for($x = 0; $x < count($inhalt); $x++)
    {
        echo '<tr><td><input type="checkbox"  name="absatz[]" class="subBox'.$i.'" value="'.$inhaltIDList[$i].','.$absatzbuchstaben[$x].'" '.$check.'>        </td>'."\n";
        echo '<td>'.$inhalt[$x].'</td></tr>'."\n";
        $check = '';
    }
}

What this does is give the First item an ID of "allBox1" and all the checkboxes after it a class name of "subBox1". Then on the next loop the first item ID becomes "allBox2" and the following check boxes class names become "subBox2".

Now when the first box is checked, "allBox1", you want to use the following jQuery to check all its child boxes :

$('body').on('click', '#allBox1' , function(e){
  if($("#allBox1").is(':checked')){
    $('.subBox1').prop('checked', true);
  }else{

  }
});

With this though you will need to copy the jQuery code for each initial box so I suggest you incorporate that into your PHP foreach loop.

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