huggyues huggyues - 8 days ago 5
Javascript Question

How to target this specific parent's checkbox when child checkbox is selected

I am having issues targetting this checkboxes parent's checkbox. I need the parent checkbox to be automatically selected whenever the child is selected. Here is my HTML. One thing which is a slight issue is that the parent div I need to select has the same class as one immediately higher in the hierarchy, which is

.checkbox


<ul class="term-reference">
<li>
<div class="checkbox">
<label class="control-label">
<input type="checkbox" class="form-checkbox">Parent Label
</label>
</div>
<ul class="term-reference">
<li>
<div class="checkbox">
<label class="control-label"">
<input type="checkbox" class="form-checkbox">Child Label
</label>
</div>
</li>
</ul>
</li>
</ul>


I have tried the following but to no avail, thank you very much for any help here

$('ul.term-reference li ul li input.form-checkbox').click(function() {
$(this).closest('.checkbox').closest('.checkbox').find('input.form-checkbox').prop('checked', true);
});

Answer

While the answers I've read here will most likely work, they appear to be tightly coupled to html (which means if you change your html, your jQuery may not work) and aren't re-useable (and have the possibility of causing other checkboxes to be checked even though they shouldn't be).

I'd recommended reading Decoupling Your HTML, CSS, and JavaScript - Philip Walton @ Google.

Slight update to your html and reusable jQuery:

    $(document).ready(function(){
      $('.checkbox-container .checkbox-child').on('click', function() {
        var $childCheckbox = $(this);
        if ($childCheckbox.is(":checked")){
          $childCheckbox
            .closest('.checkbox-container')
            .find('.checkbox-parent')
            .prop("checked", true);
        }
      });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="term-reference checkbox-container">
  <li>
    <div class="checkbox"> 
      <label class="control-label">
        <input type="checkbox" class="form-checkbox checkbox-parent">Parent Label
   	      </label>
    </div>
    <ul class="term-reference">
      <li>
        <div class="checkbox">
          <label class="control-label"">
            <input type="checkbox" class="form-checkbox checkbox-child">Child Label
          </label>
        </div>
      </li>
      <li>
        <div class="checkbox">
          <label class="control-label"">
            <input type="checkbox" class="form-checkbox checkbox-child">Child Label
          </label>
        </div>
      </li>
      <li>
        <div class="checkbox">
          <label class="control-label"">
            <input type="checkbox" class="form-checkbox checkbox-child">Child Label
          </label>
        </div>
      </li>
    </ul>
  </li>
</ul>