-3

When I click "Check all group 1", it should select its children only, but now it also selects "Check all group 2" items. How can I fix this?

Code:

jQuery(".parentCheckAll").click(function(e) {
  jQuery("#" + jQuery(this).parent().parent().attr("id") + " .extended-checkboxes input[type='checkbox']").attr('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentCheckAll"> Check all group 1</div>
<div class="extended-checkboxes">
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="1"><br />
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="2">
</div>
</div>

<div class="parentCheckAll"> Check all group 2</div>
<div class="extended-checkboxes">
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="3"><br />
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="4">
</div>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
Gold Pearl
  • 1,922
  • 3
  • 17
  • 28

1 Answers1

2

I'm not sure what you expect your code to actually do, but in order to achieve what you want, all you have to do is:

  1. Get the element with class extended-checkboxes following the clicked element and

  2. Select its input children.

Something like the following:

/* ----- JavaScript ----- */
$(".parentCheckAll").click(function(e) {
  $(this.nextElementSibling).children("input[type='checkbox']").prop('checked', true);
});
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentCheckAll"> Check all group 1</div>
<div class="extended-checkboxes">
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="1"><br />
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="2">
</div>

<div class="parentCheckAll"> Check all group 2</div>
<div class="extended-checkboxes">
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="3">
  <br />
  <input name="" type="checkbox" item="" class="checkbox-meta" tabindex="4">
</div>

Note: From jQuery 1.6 onwards, it is recommended to prefer prop instead of attr when trying to check checkboxes (See this comment).

Angel Politis
  • 10,955
  • 14
  • 48
  • 66