XiLab XiLab - 4 months ago 15
Javascript Question

jquery find parents of specific inputs and apply class

I have a selection div with checkboxes inside and I'm trying to style them with bootstrap buttons and jQuery. Each

input checkbox
takes the attribute
"checked"
by php. So what I need is:


  • find all the
    inputs
    which are 'checked', go to their
    parent
    labels and eventually
    addClass active
    .



My html (in php foreach loop)

<?php
global $wpdb;
$ss = "select * from ".$wpdb->prefix."project_email_alerts where uid='$uid'";
$rr = $wpdb->get_results($ss);
$terms = get_terms( 'project_cat', 'parent=0&orderby=name&hide_empty=0' );
foreach($terms as $term):
$chk = (KleeiaDev_check_list_emails($term->term_id, $rr) == true ? "checked='checked'" : "");?>
<div data-toggle="buttons" class="btn-group bizmoduleselect">
<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default">
<div class="bizcontent">
<input id="a-<?php echo $term->term_id ?>" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
<span class="glyphicon glyphicon-ok glyphicon-lg"></span>
<h5><?php echo $term->name ?></h5>
</div>
</label>
</div>
<?php endforeach; ?>


I've tried with jQuery at this way, searching on other similar questions without success:

if($('input').is(':checked')){
jQuery(this).parent('label').addClass('active');
}


I've tried with some use of .each but not really sure about that.

Answer

You can use

$('input[type=checkbox]:checked').parents('label').addClass('active');

    $('input[type=checkbox]:checked').parents('label').addClass('active');
.active{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label >
    <input type='checkbox' checked='true'> Check me
  <label>
</div>
  
<div>
  <label>
    <input type='checkbox'> Check me
  <label>
</div>

Comments