Zied BH Zied BH - 3 months ago 14
jQuery Question

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>




Answer

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>