mercredi 18 mai 2016

Adding class to form select parent

I have a form where only 2 checkboxes can be selected at any one time. I also need it so the container li of these checkboxes have a different background once selected. I have done this.

I'm unable to work out how to stop the class being added to the li when the user tries to select a 3rd checkbox. The jQuery stops the 3rd checkbox from being selected (which is correct); but I need the outer li to not have the class added to it.

Any help would be appreciated. I have tried hasClass, and doing if statements in the length>2 but I cannot quite grasp it.

http://ift.tt/1TYpTso

HTML

<ul class="" id="new_compare-form">
  <li class="main-table">
    <span class="ctas">
          <span class="cta cta-compare">
                <label><input type="checkbox" class="checkboxcompare" name="compare-<?php echo $product['product_id']; ?>" value="compare">Compare</label>
        </span>
    </span>
  </li>
  <li class="main-table">
    <span class="ctas">
          <span class="cta cta-compare">
                <label><input type="checkbox" class="checkboxcompare" name="compare-<?php echo $product['product_id']; ?>" value="compare">Compare</label>
        </span>
    </span>
  </li>
  <li class="main-table">
    <span class="ctas">
          <span class="cta cta-compare">
                <label><input type="checkbox" class="checkboxcompare" name="compare-<?php echo $product['product_id']; ?>" value="compare">Compare</label>
        </span>
    </span>
  </li>
</ul>

jQuery

$('input.checkboxcompare').change(function(e){
       if ($('input.checkboxcompare:checked').length > 2) {
            $(this).prop('checked', false);
       }
    })

    $('#new_compare-form :checkbox').on('click', function(){
        $(this).addClass('active');
        $(this).closest('li').toggleClass('red');
    });

CSS

.red {
  color:red;
}




Aucun commentaire:

Enregistrer un commentaire