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=".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>
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./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>
Share
Improve this question
edited Feb 28, 2016 at 14:54
Stickers
asked Feb 26, 2016 at 18:38
StickersStickers
78.8k24 gold badges155 silver badges194 bronze badges
0
2 Answers
Reset to default 9You just need change
event binding instead of click
$('.filter-set label').change(function() {
$(this).toggleClass("active");
});
Working example : http://jsfiddle/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/DinoMyte/8gz0jsnq/6/
Binding a change
event would only trigger the event once ( only for checkbox
) which would toggle the class correctly.
What you want to do here is use the checkbox change event instead:
$("input[type=checkbox]").on('change', function () {
$(this).parent().toggleClass("active");
});
Works when clicking on the checkbox directly and on the label:
https://jsfiddle/s6fx1Lez/
For more details on why this is happening:
https://stackoverflow./a/8386513/660694