Taras Yaremkiv Taras Yaremkiv - 1 month ago 5
Javascript Question

Add change event on hidden checkbox

I'm trying to catch change event, or at least click event on the checkbox. I've read that when "visibility : hidden" or "display:none", the event is not fired. Then I add eventListener to a label but it seems not working too. Can't understand how to make work.



document.addEventListener("DOMContentLoaded", function() {
var gameCount = document.getElementsByClassName("innerCount")[0];
var checkLabel = document.querySelector("input[type=checkbox] + label");
checkLabel.addEventListener("onclick", function() {
if (checkLabel.checked) {
gameCount.innerHTML = "--";
console.log("turnOn");
} else {
gameCount.innerHTML = "";
console.log("turnOff");
}
})
});

.checkbox > input[type=checkbox] {
visibility: hidden;
}
.checkbox {
display: inline-block;
position: relative;
width: 60px;
height: 30px;
border: 2px solid #424242;
}
.checkbox > label {
position: absolute;
width: 30px;
height: 26px;
background-color: #a50005;
cursor: pointer;
}
.checkbox > input[type=checkbox]:checked + label {
right: 28px;
}

<div id="switcher">
<span class="labels">ON</span>
<div class="checkbox">
<input id="checkMe" type="checkbox">
<label for="checkMe"></label>
</div>
<span class="labels">OFF</span>
</div>




Answer

Use the change event listener for checkbox fields.

document.addEventListener("DOMContentLoaded", function() {
  var gameCount = document.getElementsByClassName("innerCount")[0];
  var checkLabel = document.querySelector("input[type=checkbox]");
  checkLabel.addEventListener("change", function() {
    if (checkLabel.checked) {
      gameCount.innerHTML = "--";
      console.log("turnOn");
    } else {
      gameCount.innerHTML = "";
      console.log("turnOff");
    }
  })
});
Comments