mercredi 24 août 2016

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="http://ift.tt/1g1yFpr"></script>
<input type="checkbox" id="cbox" value="checkbox"/>
<label for="cbox">testbox</label>



Aucun commentaire:

Enregistrer un commentaire