0

I want to connect two checkbox together , so that When clicked main checkbox then checked its child. with below code I retrieve data from database:

 while($row = mysqli_fetch_array($query_show_all_receivers))
      {
          $option .= ' <pre> <input onclick="func()" type="checkbox" class="checkbox-inline" name="check_Main[]" value = "'.$row['user_username'].'">'. row['user_username'].'    
                             <input  type="checkbox" class="checkbox-inline" name="check_child[]"  id="check_child[]" value = "'.$row['user_mobile'].'">  '.$row['user_mobile'].' 
                       </pre>';

      }

and show the items:

<?php echo $option; ?>

How possible if Main box checked then will checked its child too.

Its my JavaScript code but I think have to use via loop: It just work first child not others.

        <script>
           function func()
               {
                   document.getElementById('check_child[]').checked = true ;
               }
         </script>

Thanks for your consideration.

7
  • 1
    Does this answer your question? Parent and child checkboxes Commented Apr 24, 2020 at 18:22
  • @evolutionxbox unfortunately no please help with my method Commented Apr 24, 2020 at 18:26
  • 1
    check_child[] this isn't a valid id. Consider using querySelectorAll. Commented Apr 24, 2020 at 18:27
  • @evolutionxbox yes script in that link helped me and I updated it with loop. thanks Commented Apr 25, 2020 at 8:29
  • why it dose not work with "/3.4.1/jquery.min.js" version? Commented Apr 25, 2020 at 10:46

2 Answers 2

1

IDs should be unique. In your case, you could use the query's row number in order to build an unique ID with a common prefix, it's generally good practice.

Here's a CodePen that works https://codepen.io/Raven0us/pen/abvJqLP

<label for="checkbox-parent">Parent</label>
<input type="checkbox" onchange="func(event)" name="checkbox_parent" id="checkbox-parent">

<div>
    <label for="checkbox-child-1">Child 1</label>
    <input type="checkbox" name="checkbox_child_1" id="checkbox-child-1" class="checkbox-child">
    <label for="checkbox-child-2">Child 2</label>
    <input type="checkbox" name="checkbox_child_2" id="checkbox-child-2" class="checkbox-child">
    <label for="checkbox-child-3">Child 3</label>
    <input type="checkbox" name="checkbox_child_3" id="checkbox-child-3" class="checkbox-child">
</div>

I changed onclick to onchange, some people prefer click, mostly for legacy reasons (I think?), but I wouldn't. Moreover, I passed the actual event to the function, so it's available if we want to check stuff about it.

function func(event) {
    document.querySelectorAll('.checkbox-child').forEach(checkboxChild => {
        checkboxChild.checked = event.target.checked;
    })
}

The handler gets all the related checkboxes, based on a common class which can repeat, unlike IDs, and loop through the returned NodeList and update their value based on parent checkbox value. So, checking or unchecking parent will update children as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Ravenous , but children’s id are in loop idk how many are there to set unique id. It retrieves from database
Before while, you can simply have a variable $index = 0;, and for each row, you just increment that $index++, and use $index when setting up your markup so you'll get unique IDs. To get it working like it does in the example, you don't need the IDs, though.
0

Parent and child checkboxes

with above script by @CoolEsh I could solve this problem and update with loop to specific every parents and their children :

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"> </script>
  <script>
        var checkboxHandlerObj = {
  init: function() {
    $('#customerServices input:checkbox[class="parent"]').click(checkboxHandlerObj.parentClicked);
    $('#customerServices input:checkbox[class^="parent-"]').click(checkboxHandlerObj.childClicked);
  },

  parentClicked: function() {
    if ($(this).attr('checked')) {
      $('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').attr('checked', 'checked');
    } else {
      $('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').removeAttr('checked');
    }
  },

  childClicked: function() {
    var temp = $(this).attr('class').split('-');
    var parentId = temp[1];

    if ($(this).attr('checked')) {
      $('#' + parentId).attr('checked', 'checked');
    } else {
      var atLeastOneEnabled = false;
      $('#customerServices input:checkbox[class="' + $(this).attr('class') + '"]').each(function() {
        if ($(this).attr('checked')) {
          atLeastOneEnabled = true;
        }
      });
      if (!atLeastOneEnabled) {
        $('#' + parentId).removeAttr('checked');
      }
    }
  }

};

checkboxHandlerObj.init();

         </script>

and PHP loop:

<div id="customerServices">
<?php
$x = 1;
$id = 1;
while($x <= 5) {
    $x++;
$option .= '<input id="'.$id.'"  class="parent" type="checkbox" name="check_Main[]" value = "1">1
<input  type="checkbox" name="check_child[]" class="parent-'.$id.'"  value = "2">  2 <br> ';

$id++ ;
} 

 echo $option;
?>
</div>

It worked with unique Id. Thanks For @Ravenous and @evolutionxbox

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.