samedi 30 juillet 2016

jQuery - Limit groups of labels and checkboxes to a max number

I'm trying to limit a max number selectable for checkboxes and their relative labels. Checkboxes work fine but labels are still selectable more than the limit.

My html input is formed like this:

<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default <?php echo $labelchk ?>">
    <div class="bizcontent">
        <input id="youaresure" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
        <h5><?php echo $term->name ?></h5>
    </div>
</label>

and my jQuery to limit checkboxes and labels is like:

var $checkboxes = $('input[id="youaresure"]');
var $parent = $checkboxes.parent('label');
var max = 5;
$checkboxes.show();
$checkboxes.change(function () {
    $(this).prop('checked', function () {
        if ($(this).is(':checked')) {
            return ($checkboxes.filter(':checked').length <= max) ? true : false;
        }
    });
});
$parent.show();
$parent.change(function () {
    $(this).prop('class', function () {
        if ($(this).is('active')) {
            return ($parent.filter('active').length <= max) ? true : false;
        }
    }

Basically, php inserts an active class to labels parents of inputs:checked and I should prevent both labels and inputs to be selected if more than 5. For checkboxes is fine but parent labels are still selectable and basically are the visible ones.




Aucun commentaire:

Enregistrer un commentaire