Run function according to the status of a checkbox

4

Good people, it turns out that I have a theme, I'm doing an interface to control an arduino that I have, and what I did was with JavaScript send a GET request when you press the power button and another by pressing the power off button, which I want to use a checkbox and that when selecting it the function on() is executed and when you select it the function off()

<script type="text/javascript">

function on2() {
  if (window.XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
  } else {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  var url = "http://192.168.0.104/r2=ON";
  xmlhttp.open("GET", url, false);
  xmlhttp.send(null);
  var respo= xmlhttp.responseText;
  
 }

 function off2() {
  if (window.XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
  } else {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  var url = "http://192.168.0.104/r2=OFF";
  xmlhttp.open("GET", url, false);
  xmlhttp.send(null);
  var respo= xmlhttp.responseText;
  
 }
</script>
    
asked by Santiago D'Antuoni 31.12.2016 в 16:58
source

2 answers

5

You can make a condition by checking if the checkbox is true or false with the checked attribute of the checkbox.

Then you can assign an event to the checkbox to run when it has changed its status using the addEventListener function and telling it to run with the change event.

Example:

function on(){
  console.log("Hemos pulsado en on");
}

function off(){
  console.log("Hemos pulsado en off");
}

var checkbox = document.getElementById('checkbox');

checkbox.addEventListener("change", comprueba, false);

function comprueba(){
  if(checkbox.checked){
      on();
  }else{
     off();
  }
}
<input id="checkbox" type="checkbox">
    
answered by 31.12.2016 / 17:04
source
0

You can do it like this:

var checkBox = document.querySelector('#iddetucheckbox');
checkBox.addEventListener('change', verificarEstado, false);

function verificarEstado(e) {
    if(e.target.checked){
        on();
    }else{
        off();
    }
}
    
answered by 31.12.2016 в 17:22