I have an HTML checkbox element, with a Label element linked to it by the "for" attribute of Label, I tried to check/uncheck the checkbox element by capturing the click event of the Label element,
Can somebody tell why this code does the opposite of what is intended,
$("label").click(function() {
$(this).toggleClass("active");
if ($(this).hasClass("active")) {
$("#checker").prop("checked", true);
console.log("checked");
}
else {
$("#checker").prop("checked", false);
console.log("unchecked");
}
});
.active {
background: green;
color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for='checker'>Check it</label>
<input type='checkbox' id='checker'>
Whereas this code works just fine.
$("label").click(function(){
$(this).toggleClass("active");
if($(this).hasClass("active")){
setTimeout(function(){
$("#checker").prop("checked",true);
},0);
console.log("checked");
}
else{
setTimeout(function(){
$("#checker").prop("checked",false);
},0);
console.log("unchecked");
}
});
.active {
background: green;
color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for='checker'>Check it</label>
<input type='checkbox' id='checker'>
Aucun commentaire:
Enregistrer un commentaire