So, we have a checkbox and a label associated with it. I need to toggle the checkbox state by clicking on the label and uncheck it if I click anywhere else on the body. The problem with the code below is that the checkbox could not be unchecked by clicking on the label.
$(function () {
"use strict";
function uncheckBox() {
var isChecked = $("#cbox").prop("checked");
if (isChecked) {
$("#cbox").prop("checked", false);
}
}
$("body").on("click", function () {
uncheckBox();
});
$("#cbox").on("click", function (e) {
e.stopPropagation();
});
});
html, body {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" id="cbox" value="checkbox"/>
<label for="cbox">testbox</label>
By using jQuery function prop() you can dynamically add this attribute or if present we can change its value i.e. checked=true to make the checkbox checked and checked=false to mark the checkbox unchecked.
Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc. The prop() method require jQuery 1.6 and above.
Once the checkbox is selected, we are calling prop() function as prop( "checked", true ) to check the checkbox and prop( "checked", false ) to uncheck the checkbox.
The simple answer is NO, CSS cannot help you uncheck the checkbox.. You can use CSS to detect whether the input element is checked or not by using :checked and :not(:checked) ..
Stop the event bubbling that occurs from label also, $("#cbox,label").click
$(function () {
"use strict";
function uncheckBox() {
var isChecked = $("#cbox").prop("checked");
if (isChecked) {
$("#cbox").prop("checked", false);
}
}
$("body").on("click", function () {
uncheckBox();
});
$("#cbox,label").on("click", function (e) {
e.stopPropagation();
});
});
html, body {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" id="cbox" value="checkbox"/>
<label for="cbox">testbox</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