Jason Jason - 6 months ago 19
jQuery Question

Automatically check parent when child is checked

When any checkbox with class .child-term is checked, I automatically need to check the preceding checkbox with class .parent-term.

I only want to check the preceding .parent-term class not all the checkboxes that have .parent-class. Same goes for the .child-term class. Any checkbox with .child-term only affects the .parent-term above.

If the .parent-term class was checked from a .sub-term checkbox the .parent-term can remain checked when all the associated .sub-term boxes are unchecked.

I have tried various solutions, but I can't figure it out.

I started a jsfiddle.

<ul class="cpt-terms-checkbox">
<li class="parent-term church" id="category-church"><input id="church"
name="church" type="checkbox" value="church">Church</li>

<li><small>Sub Categories:</small></li>

<li class="child-term elder" id="category-elder"><input id="elder"
name="elder" type="checkbox" value="elder">Elder</li>
<li class="child-term interim-pastor" id="category-interim-pastor">
<input id="interim-pastor" name="interim-pastor" type="checkbox" value=
"interim-pastor">Interim Pastor</li>

<li class="parent-term law-firm" id="category-law-firm"><input id=
"law-firm" name="law-firm" type="checkbox" value="law-firm">Law
Firm</li>

<li><small>Sub Categories:</small></li>

<li class="child-term attorney" id="category-attorney"><input id=
"attorney" name="attorney" type="checkbox" value=
"attorney">Attorney</li>
<li class="child-term attorney" id="category-attorney"><input id=
"attorney" name="attorney" type="checkbox" value=
"attorney">Paralegal</li>
</ul>


Adding to Anoop Joshi's solution . . . I changed .parent() to .parents() so it would move up higher and for those who may run this in Wordpress I wrapped it in an anonymous function.

(function($) {
$(".child-term :input").change(function() {
if (this.checked) {
$(this).parents().prevAll(".parent-term:first").find("input").prop("checked", true);
}
});
})( jQuery );

Answer

Use prevAll() to get all the previous nodes with specified selector.

Then you can use the :first selector to get the immediate previous element

$(".child-term :input").change(function() {
  if (this.checked) {
    $(this).parent().prevAll(".parent-term:first").find("input").prop("checked", true);
  }
});

Fiddle

Comments