Toggle Switch Back To Off
I trying to create a function which reverts toggle switches back to off. I'm turning a light on or off with my switch but there is a button and if i press that I want all the light
Solution 1:
I have created an example app for you here. https://codesandbox.io/embed/lucid-brook-q6qsq
The idea is to use document.querySelectorAll
and iterate over all the checkboxes and uncheck them. Here is the relevant code:
document.querySelector("#stop").addEventListener("click", () => {
const switches = document.querySelectorAll(".switch input");
for (let s of switches) {
s.checked = false;
}
});
Solution 2:
I recommend you look up querySelectorAll
window.addEventListener("load", function() {
document.getElementById("stop").addEventListener("click", function() {
[...document.querySelectorAll(".switch input[type=checkbox]")].forEach(function(chk) {
chk.checked = false; // and perhaps add chk.onchange() if needed
});
});
});
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */.switchinput {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked+.slider {
background-color: #2196F3;
}
input:focus+.slider {
box-shadow: 001px#2196F3;
}
input:checked+.slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
<labelclass="switch"><inputtype="checkbox"name="one"id="one"><spanclass="slider round"></span></label><labelclass="switch"><inputtype="checkbox"name="two"id="two"><spanclass="slider round"></span></label><labelclass="switch"><inputtype="checkbox"name="three"id="three"><spanclass="slider round"></span></label><labelclass="switch"><inputtype="checkbox"name="four"id="four"><spanclass="slider round"></span></label><br><inputtype="button"id="stop"value="Stop All" /><br>
Alternative code for ancient browsers
var chks = document.querySelectorAll(".switch input[type=checkbox]");
for (var i=0;i<chks.length;i++) chks[i].checked = false;
Solution 3:
in JavaScript you'll use the getElementsByClassName()
method. You'll have to add a class to all of your checkboxes, alternatively you can use getElementsByTagName()
to target the checkbox tags.
let switches = document.getElementsByClassName("checkboxClass");
then iterate thru the class with JavaScript
for (let i = 0; i < switches.length; i++) {
switches[i].checked = false;
}
this will turn them all off. you can put this in a function and call it whenever (onclick
/onchange
, etc.)
Hope this helps, good luck!
Post a Comment for "Toggle Switch Back To Off"