Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggleClass doesn't work with label

Why doesn't toggleClass() work with label element? And how can I fix it?

If you only click on the label (not the checkbox) you'll see the color doesn't change.

jsFiddle

$(document).ready(function() {
  $('.filter-set label').click(function() {
    $(this).toggleClass('active');
  });
});
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filter-set">
  <ul>
    <li><label><input name="checkbox" type="checkbox"> label 1</label></li>
    <li><label><input name="checkbox" type="checkbox"> label 2</label></li>
    <li><label><input name="checkbox" type="checkbox"> label 3</label></li>
  </ul>
</div>
like image 554
Stickers Avatar asked Dec 07 '22 23:12

Stickers


1 Answers

You just need change event binding instead of click

$('.filter-set label').change(function() {
    $(this).toggleClass("active");
  });

Working example : http://jsfiddle.net/DinoMyte/8gz0jsnq/5/

Explanation :

It turns out that when you click on the label, it also invokes the click event on the input:checkbox ( because of nested element wrapping ). Because of this, the 1st event on the label does sets the class 'active' correctly , however with the subsequent click event on the checkbox toggles it back to empty ( basically removes the class 'active').

The effects of the above mentioned can be seen here : http://jsfiddle.net/DinoMyte/8gz0jsnq/6/

Binding a change event would only trigger the event once ( only for checkbox ) which would toggle the class correctly.

like image 94
DinoMyte Avatar answered Mar 02 '23 01:03

DinoMyte