Reputation: 432
I have a switch button(0/1 Button). I click one time but return both 0 and 1 together. I need return 0 OR 1
<label class="switch s-outline s-outline-success">
<input type="checkbox" name="product-images-check" class="checkbox_check">
<span class="slider round"></span>
</label>
Jquery - JS
$("label").on("click", function() {
if($(this).children("input").is(":checked")) {
console.log("Checkbox is checked.");
}
else if($(this).children("input").is(":not(:checked)")) {
console.log("Checkbox is unchecked.");
}
console.log("CLICKED");
})
Upvotes: 2
Views: 291
Reputation: 89294
Attach the event listener to the checkbox instead of the label.
$("label > input[type=checkbox]").on("click", function() {
if ($(this).is(":checked")) {
console.log("Checkbox is checked.");
} else {
console.log("Checkbox is unchecked.");
}
console.log("CLICKED");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch s-outline s-outline-success">
<input type="checkbox" name="product-images-check" class="checkbox_check">
<span class="slider round">Click me</span>
</label>
Upvotes: 1
Reputation: 1099
Simply remove the condition inside else if and make it else block.
$("label").on("click", function() {
if($(this).children("input").is(":checked")) {
console.log("Checkbox is checked.");
}
else {
console.log("Checkbox is unchecked.");
}
console.log("CLICKED");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch s-outline s-outline-success">
<input type="checkbox" name="product-images-check" class="checkbox_check">
<span class="slider round"></span>
</label>
Upvotes: 0