Search code examples
javascriptjquerycheckboxsiblings

Click Label if checkbox prop check is true


All check boxes by default are unchecked. I cannot use radio buttons in the problem.

When a checkbox is changed to 'checked' then look to see if any of the sibling checkboxes are 'checked', if it is then .click() the parent <label> of the checkbox.

I have to .click() the <label> because the connected API is listening for a click on the label, $('input').prop("checked", false); doesn't seem to work.

Here is the structure:

<div class="feature-filter">
  <div id="filterHandle">Product Filter</div>
  <label class="featureLabel">
    <input class="featureCheck" type="checkbox">
    Original Pouch
  </label>
  <label class="featureLabel">
    <input class="featureCheck" type="checkbox">
    Original Can
  </label>
  <label class="featureLabel">
    <input class="featureCheck" type="checkbox">
    Gold Pouch
  </label>
  <label class="featureLabel">
    <input class="featureCheck" type="checkbox">
    Gold Can
  </label>
  <label class="featureLabel">
    <input class="featureCheck" type="checkbox">
    Menthol Pouch
  </label>
  <label class="featureLabel">
    <input class="featureCheck" type="checkbox">
    Menthol Can
  </label>
</div>

This is what i tried but it's wrong.

       $('.featureCheck').click(function(){

            if $('.featureCheck').siblings().prop('checked',true){
                this.find('label').click();
            }

        });

Solution

  • It sounds like you want something like this:

    $('.featureCheck').change(function() {
      if (this.checked) {
        $('.featureCheck').not(this).filter(':checked').closest('.featureLabel').click();
      }
    });
    

    So if you check a checkbox, find others which are checked, and trigger the click event on their parent label