I have this code:
<label><input type="checkbox">True?</label>
and
$("label").click(function () {
$(this).toggleClass("active");
});
When I click the checkbox class toggles, when I click "True?" nothing happens. Why?
Then if I don't wrap checkbox in label everything works fine.
<input type="checkbox" id="c1"><label for="c1">True?</label>
This is so weird... And it doesn't matter if I put "for" or not.
http://jsfiddle.net/zufs6ueh/1/
What is going wrong here?
This would be safer to use:
$(function() {
$('input[type="checkbox"]').bind('change', function (v) {
if($(this).is(':checked')) {
$(this).parent().addClass('active');
} else {
$(this).parent().removeClass('active');
}
});
});
Using change
instead of click
allows for people that navigate forms using the keyboard.
Clicking the label also triggers a click on the input so bind the change event to the checkbox itself:
$(function(){
$("label input").on("click",function(){
$(this).parent().toggleClass("active");
});
});
.active {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox" />True?</label>
If you don't need to support old browsers, you could use the :checked
pseudo-class in CSS instead:
input[type=checkbox]:checked + label {color:red;}
<input type="checkbox" id="demo" name="demo">
<label for="demo">True?</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With