3

I have been trying to make a toggle switch that enables/disables a part of my program. The code I use for making the button is taken from here w3schools

Now I wanted to add the functionality to the button, but was completely stuck. What I want to do, is if the switch is pressed, I want my program to active part of my code which enables a setting, or if the switch is already on, to disable it.

So what I'm looking for, is a way to get the value of the switch somewhere, and using that in something like an if statement, like:

if(switch== on){ 
   //do this;
} else{ 
   //do that;
}

I hope it is clear what I wanted to say. Any help is appreciated.

Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106
JoJoDeath
  • 75
  • 1
  • 1
  • 6

5 Answers5

14

I don't know if that is what you want, but often, you want to listen for an event that triggers when the checked state changes:

document.addEventListener('DOMContentLoaded', function () {
  var checkbox = document.querySelector('input[type="checkbox"]');

  checkbox.addEventListener('change', function () {
    if (checkbox.checked) {
      // do this
      console.log('Checked');
    } else {
      // do that
      console.log('Not checked');
    }
  });
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {display:none;}

.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: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}
<h2>Toggle Switch</h2>

<label class="switch">
  <input type="checkbox">
  <div class="slider"></div>
</label>

When the browser parses your HTML and reaches a <script> tag, it immediately executes the JavaScript in it. It can however happen, that the rest of the document is not loaded yet.

This means that some of the HTML elements in the page don't exist yet, and you can't access them in JavaScript. You have to wait until the elements are loaded.

Fortunately, the browser fires an event when it is done loading the contents of the page. This event is called DOMContentLoaded.

When you wait for the browser to first fire the event, you can be sure that you can access all elements in the DOM.

PeterMader
  • 6,987
  • 1
  • 21
  • 31
  • I've tried this out, and if I check the console, I get an error message that it cannot read property addEventListener. It doesn't show anything in the console there either. I'm fairly new to using javascript in general, so I have no idea what to do with this. Can you recommand a way to get rid of the error, or maybe give something that displays on the webpage when I click it? – JoJoDeath Jun 16 '17 at 15:28
  • It depends on how you load the JavaScript. When the code that I posted runs, the checkbox element has to be loaded. If it isn't, `document.querySelector` will return `null`, and you can't read a property of null. It should work with my updated anwer. – PeterMader Jun 16 '17 at 15:34
  • ah yes, it works now. What exactly is it that the first line does now? I'm curious to know what it did, and why it made it work. – JoJoDeath Jun 16 '17 at 15:40
  • So I've been working on other parts of the webpage, and just found out something that I don't understand how to fix: When I turn the switch to "on", it goes to on, but if I go to a different page, and go back to the page with the slider, it is actually in the "off" position again. I think I need to make the switch show the position based on the value of the switch(ProgramState="on" or "off"), but I don't know how to do that. Do you have any tips/ideas to make this work? – JoJoDeath Jun 22 '17 at 08:07
  • You mean the browser doesn't remember the state of the checkbox when you open it again? – PeterMader Jun 22 '17 at 13:07
  • it does remember the value that I give to it. When I press the switch it turns on, and the value for ProgramState changes. This value is remembered, so the result is the same. But the visuals of the switch turn back to how it starts normally: in the "off" position, even though the value of ProgramState has the right value, "on". I was wondering how I could make it such that the webpage checks for what the value is, and corresponding to the value has the switch be displayed either to the left, or to the right("off" and "on" values respectively). – JoJoDeath Jun 23 '17 at 15:45
3

Use the checked value of the checkbox element to see the current state

Also See Oded's answer on this post on the usage of the property within HTML.

Within JavaScript, you can retrieve the element in whatever flavour you like, and then simply see what the value of the checked attribute is.

Working Sample:

function getValue() {
   var isChecked = document.getElementById("myCheckBox").checked;
    
   if(isChecked){
     console.log("Input is checked");
   } else {
     console.log("Input is NOT checked");
   }
}
<label>
  <input id="myCheckBox" type="checkbox" > Toggle me
</label>

<br>
<br>

<button onclick="getValue()">Check value of above input</button>
Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106
2

You can solve this using JQuery. Attach a change event to the input checkbox element.

<input type="checkbox" id="myToggle"/>

$('#myToggle').change(function(){
    if(this.checked) {
        do this;
    }
    else {
        do that;
    }
});
Karan Hudia
  • 553
  • 3
  • 19
2

Here is a really basic one:

function doStuff() {
    console.log("Hello World!")
}
function toggle(button) {
    if(button.value=="OFF") {
        button.value="ON"
        button.innerHTML="ON"
        this.interval = setInterval(doStuff, 1000);
    } else if(button.value=="ON") {
        button.value="OFF"
        button.innerHTML="OFF"
        clearInterval(this.interval)
    }
}
<button onclick="toggle(this)" value="OFF">OFF</button>
Forivin
  • 14,780
  • 27
  • 106
  • 199
1

It is just a checkbox. You can do like this -->

$(document).ready(function(){
 $('#on').on('change',function(){
     if(this.checked){
      $("#info").text("U checked me, place some code here");
     }
        else{
         $("#info").text("U unchecked me, another piece of code here");
        }
    });
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {display:none;}

.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: 0 0 1px #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%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
  <input id="on" type="checkbox">
  <div class="slider"></div>
</label>
<p id="info"></p>

Just place your piece of code in if-else block.

Rabinder Bisht
  • 584
  • 2
  • 7
  • 19