Uncheck the box by clicking anywhere in the body and toggling it by clicking on its label

So, we have a flag and a label associated with it. I need to switch the state of the checkbox by clicking on the shortcut and uncheck it if I clicked elsewhere on the body. The problem with the code below is that the checkbox cannot 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>
Run codeHide result
+4
source share
1 answer

Stop bubbling events that also occur with a label, $("#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>
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1652314/


All Articles