Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncheck a checkbox by clicking anywhere on the body and toggle it by clicking its label

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>
like image 897
Zied BH Avatar asked Aug 24 '16 09:08

Zied BH


People also ask

How do you uncheck a checkbox?

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.

How do I uncheck a checkbox dynamically?

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.

How do you uncheck a checkbox in Python?

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.

How do I uncheck a checkbox in CSS?

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) ..


1 Answers

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>
like image 111
Rajaprabhu Aravindasamy Avatar answered Oct 14 '22 04:10

Rajaprabhu Aravindasamy