Kann Kann - 5 months ago 17
jQuery Question

add highlight class to the label of a checked check box via a button

I have checked all over stack overflow, but they're not exactly what I need.
I have checkboxes with associated labels

<p>
<input type="checkbox" name="animals" value="dog" id="dg" />
<label for="dg">Dog</label>
</p>
<p>
<input type="checkbox" name="animals" value="cat" id="ct" />
<label for="ct">Cats</label></p>
<p>

<p><input type="button" id='bt' value="Record" /></p>


There is also a button, when the button is clicked, if the checkbox is checked, the label associated with it has a highlight class added to the label. I already have the highlight class written I am just having trouble applying it using the addClass method.

I have:

$(':checkbox:checked').addClass('highlight');


but it does nothing

Answer

Update: Okay, I think I understand what you need. See updated example.


The trick is knowing how to find the label and checkbox associated with the button. Since the buttons were not included in the question code, I had to guess. If the button is elsewhere, you can experiment using these jQuery traversing methods.

$(document).ready(function(){
  
$('#mybutt').click(function(){
  var chkboxes = $('input[type=checkbox]');
  $(chkboxes).each(function(){
     if ( $(this).is(':checked') ){
         $(this).parent().find('label').addClass('highlight');
     }else{
         $(this).parent().find('label').removeClass('highlight');
     }
  });
});
  
}); //END document.ready
.highlight{background:red;color:yellow;padding:2px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>
  <input type="checkbox" name="animals" value="dog" id="dg" />
  <label for="dg">Dog</label>
</p>
<p>
  <input type="checkbox" name="animals" value="cat" id="ct" />
  <label for="ct">Cats</label>
<p>
<button id="mybutt">Go</button>