Jquery check /uncheck all checkboxes when click a button

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
mlucicom
Posts:37

Jquery check /uncheck all checkboxes when click a button

Hello! I have this jquery script that get all checkboxes from a div and check all at button click:

Code: Select all

 <script>
 $("#check'.$id22.'").click(function(){ 
  $("#check'.$id22.'").find("input[type=checkbox]").each(function () {
    // some staff
    this.checked = true;
  });
});
</script>
At a second click on the same button, how can i uncheck all checkboxes?
When clicking the button, the script must check/uncheck only the checkboxes from specified div.
I have many div that have checkboxes .

Admin Posts:805
Hello
Try addapt the code from this example to your script:

Code: Select all

<div id="check1">
<input type="checkbox" value="1" />Chb-1 
<input type="checkbox" value="2" />Chb-2 
<input type="checkbox" value="3" />Chb-3<br>
<button id="1" class="btns">Click</button>
</div>
<div id="check2">
<input type="checkbox" value="1" />Chb-1a 
<input type="checkbox" value="2" />Chb-2a 
<input type="checkbox" value="3" />Chb-3a<br>
<button id="2" class="btns">Click</button>
</div>
<script>
//check, uncheck all checkbox in div (a css selector)
function chkUnchk(div){
  $(div).find("input[type=checkbox]").each(function(){ //parse all checkbox from div
    if($(this).attr("checked")){
      $(this).removeAttr("checked");
      $(this).prop("checked",false);
    }
    else{
      $(this).attr("checked", "checked");
      $(this).prop("checked",true);
    }
  });
}

//when click the button call chkUnchk() with id of div with checkboxes
$(".btns").click(function(){
  chkUnchk("#check"+$(this).attr('id'));
});
</script>
- Demo:
Chb-1 Chb-2 Chb-3
Chb-1a Chb-2a Chb-3a

mlucicom Posts:37
I tried to adapt this code at my script, but this don' work

Code: Select all

<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

 require('layout.php');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = ".. ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $var = $row["GROUP_CONCAT(area.id ORDER BY area.id SEPARATOR ', ')"];
      $location = $row['location'];
      $id22= $row['id22'];

      $each=explode(', ',$var);
       echo '<form action="report.php?id='.$id22.'" method="post">
       <div id="'.$id22.'">
              <div class="col-md-3">
          <div class="box box-warning">
            <div class="box-header with-border">
              <h3 class="box-title"><input type="checkbox" name="data2[]" value="'.$location.'">'.$location.'</h3>
              <button type="button" id="'.$id22.'" class="btns">Click</button>

              <div class="box-tools pull-right">
                <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
                </button>
              </div>
              <!-- /.box-tools -->
            </div>
            <!-- /.box-header -->
            <div class="box-body" id="content'.$id22.'">
              
            </div>
             <a href="contact.php?id='.$id22.'">
         <button type="button" class="btn btn-default btn-sm">
          <span class="glyphicon glyphicon-envelope"></span> Contact 
        </button></a>
         <a href="report.php?id='.$id22.'">
                 <button type="submit" class="btn btn-default btn-sm">
          <span class="glyphicon glyphicon-warning-sign"></span>Report 
        </button></a>
         <a href="satisfaction.php?id='.$id22.'">
         <button type="button" class="btn btn-default btn-sm">
          <span class="glyphicon glyphicon-heart-empty"></span>Satisfaction 
        </button></a>


            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
        </div>';
$link2 = "http://elitservice.dk/sistem/area";
foreach($each as $v){
$q=$conn->query("SELECT  `area`.`id` AS `area_id22`  , `area`.`area` , `area`.`id_principal` AS `id22`  ,  `area_description`.`id`  , `area_description`.`description` , `area_description`.`id_area`,GROUP_CONCAT(area_images.patch ORDER BY area_images.patch SEPARATOR ', ') FROM  `area` , `area_description`, `area_images` WHERE  `area`.`id` ='" . $v. "' AND `area_description`.`id_area` = `area`.`id` AND `area_images`.`id_area` =  `area`.`id` GROUP BY `area`.`area`   " );


           foreach($q as $cat){
            $id_p = $cat['area_id22'];
            $area_id = $cat['area_id22'];
            $area = $cat['area'];
$descriere = $cat['description'];
$imagini = $cat["GROUP_CONCAT(area_images.patch ORDER BY area_images.patch SEPARATOR ', ')"];
echo '<script type="text/javascript">
var theDiv = document.getElementById("content'.$id22.'");

//Here we escape single quotes in php string, to have double-quotes inside string with single-quotes in JS
theDiv.innerHTML +=\'<button type="button" data-toggle="collapse" class="btn btn-info" data-target="#'. str_replace('"', '\"', $id_p) .'"><input type="checkbox" name="data2[]" value="'.$area.'">'. str_replace('"', '\"', $area) .' </button><br/><div id="'. str_replace('"', '\"', $id_p) .'" class="collapse">'. str_replace('"', '\"', $descriere) .'</div><br/>\';
</script>';

$myArray = explode(',',$imagini);
foreach($myArray as $value){ 
    echo '<script type="text/javascript">
var theDiv = document.getElementById("'.$id_p.'");
theDiv.innerHTML +=\'<br/><img src="http://elitservice.dk/sistem/area/'.ltrim($value).'" alt="Smiley face" height="100" width="100">\';
</script>';
}

      $linkq=$conn->query(" SELECT  `section`.`section` ,`section`.`id` AS `idse`, `section_description`.`description` ,GROUP_CONCAT(section_images.patch2 ORDER BY section_images.patch2 SEPARATOR ', ') FROM  `section` , `section_description`, `section_images` WHERE  `section`.`area_id` ='" . $cat['area_id22'] . "' AND `section_description`.`area_id` = '" . $cat['area_id22'] . "' AND `section`.`id` = `section_description`.`section_name` AND `section_images`.`section_name` = `section`.`id`  AND `section_images`.`area_id` = '" . $cat['area_id22'] . "' GROUP BY `section`.`section`  "); 
  foreach($linkq as $link){ 
    $idse = $link['idse'];
    $section =$link['section'];
    $desc = $link['description'];

$imagini2 = $link["GROUP_CONCAT(section_images.patch2 ORDER BY section_images.patch2 SEPARATOR ', ')"];

    echo '<script type="text/javascript">
var theDiv = document.getElementById("'.$id_p.'");

//Here we escape single quotes in php string, to have double-quotes inside string with single-quotes in JS
theDiv.innerHTML +=\'<br/><button type="button" data-toggle="collapse" style="margin: -20px -50px;position:relative;top:50%;left:50%;" class="btn btn-warning" data-target="#'. str_replace('"', '\"', $idse) .'"><input type="checkbox" name="data2[]" value="'.$section.'">'. str_replace('"', '\"', $section) .' </button><br/><div id="'. str_replace('"', '\"', $idse) .'" class="collapse">'. str_replace('"', '\"', $desc) .'</div>\';
</script>';
$myArray2 = explode(',',$imagini2);
foreach($myArray2 as $value2){ 
    echo '<script type="text/javascript">
var theDiv = document.getElementById("'.$idse.'");
theDiv.innerHTML +=\'<br/><img src="http://elitservice.dk/sistem/area/'.ltrim($value2).'" alt="Smiley face" height="100" width="100">\';
</script>';
}
     }
     
    }
    
}
}
}
      
    
 else {
    echo "0 results";
}
$conn->close();

?>
<script>
//check, uncheck all checkbox in div (a css selector)
function chkUnchk(div){
  $(div).find("input[type=checkbox]").each(function(){ //parse all checkbox from div
    if($(this).attr("checked")){
      $(this).removeAttr("checked");
      $(this).prop("checked",false);
    }
    else{
      $(this).attr("checked", "checked");
      $(this).prop("checked",true);
    }
  });
}

//when click the button call chkUnchk() with id of div with checkboxes
$(".btns").click(function(){
  chkUnchk("#check"+$(this).attr('id'));
});
</script>

Admin Posts:805
Hy,
To much code and i cannot test it because i not have the necessary database.
Study better the example I have gave above, that it works.
- If the <button> has:

Code: Select all

id="'.$id22.'"
- the associated Div with checkboxes must have:

Code: Select all

id="check'.$id22.'"