0

I'm struggling with a power button that is supposed to run two different cgi scripts when it is pressed.

I have some code like so (I've truncated the code between<main> tags) :-

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body class="site">
<main>
<button href="#" class="buttonb" onclick="onoff()"><img class="on-button" src="images/power.png" alt="ON"></button>
</main>
<script>
var isOn=false;
function onoff()
{
  if(isOn)
{
  window.location.href="/cgi-bin/turnon.pl";
  var isOn=true;
}else
{
  window.location.href="/cgi-bin/turnoff.pl";
  var isOn=false;
}
}
</script>
</body> 
</html>

I have some css formatting things so it looks better too.

For some reason no matter what I do I can only get the else option to run on every button push. ie. it only runs the off script. The individual scripts do what is intended when run from the console.

Can someone shed some light on what is going on or maybe suggest another way of achieving the same thing? I'm a newbie to this stuff if that makes a difference

Thanks Steve

Steve W
  • 53
  • 7

1 Answers1

0

You are defining a local variable isOn instead of setting the value of the global variable isOn.

The logic is also incorrect where isOn is defined as false initially

<button href="" class="buttonb" onclick="onoff()"><img class="on-button" src="" alt="ON"></button>
<script>
  var isOn = false;

  function onoff() {
    if (!isOn) {
      isOn = true;
      console.log(isOn)
    } else {
      isOn = false;
      console.log(isOn)
    }
  }
</script>
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thanks for that - some progress :) it seems that I need to double click to toggle the second time round which is a bit odd. any ideas – Steve W Jul 23 '17 at 06:52
  • @SteveW Do not need to double click, here. Each click toggles `Boolean` value, as demonstrated at stacksnippets – guest271314 Jul 23 '17 at 13:12
  • I've got to be missing something? I can't get it to switch between the two scripts. `code`var isOn = false; function onoff(){ if(!isOn) { isOn=true; console.log(!isOn); window.location.href="/cgi-bin/ToshibaACPWROFF.pl"; } else { isOn=false; console.log(isOn); window.location.href="/cgi-bin/ToshibaACPWRON.pl"; } }`code` The two perl scripts work fine on their own buttons – Steve W Jul 24 '17 at 09:07
  • and double clicking still works if I wait a few seconds? – Steve W Jul 24 '17 at 09:18
  • If you are setting `window.location.href` then the variable will be reset at each click. See [Global Variable usage on page reload](https://stackoverflow.com/questions/29986657/global-variable-usage-on-page-reload) – guest271314 Jul 24 '17 at 13:53
  • Genius! local.storage seems to do exactly what is needed. – Steve W Jul 25 '17 at 09:16