-1

I try to make a On and Off button in html and but when I put the tag input inside the Form doesn't work it stay on off doesn't switch to On

function onoff() {
  currentvalue = document.getElementById('onoff').value;
  if (currentvalue === "Off") {
    document.getElementById("onoff").value = "On";
  } else {
    document.getElementById("onoff").value = "Off";
  }
}
<form action="" method="post">
  <input type="button" value="Off" id="onoff" onclick="onoff();" class="button button2">
</form>
Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
Alsukayt
  • 1
  • 1

2 Answers2

0

Try this:

<form action="" method="post">
  <input type="button" value="Off" id="onoff" onclick="document.getElementById('onoff').value==='Off'?document.getElementById('onoff').value='On':document.getElementById('onoff').value='Off';" class="button button2">
</form>
Luka Darsalia
  • 79
  • 1
  • 4
0

You may just rename your function name to not match id of the clicked target and your code will work:

function onoffHandler() {
    currentvalue = document.getElementById('onoff').value;
    if (currentvalue === "Off") {
        document.getElementById("onoff").value = "On";
    } else {
        document.getElementById("onoff").value = "Off";
    }
}
<form action="" method="post">
    <input type="button" value="Off" id="onoff" onclick="onoffHandler();" class="button button2">
</form>

This happens because a legacy scope being injected into the scope chain. But only for inline handlers. That allows to address all your forms' elements having id or name attribute by the same variable names. And since those id and name variables are in higher (closer) scope they shadow all other functions or variables with the same names.

If you need more thorough explanation what exactly is happening you may check out this [answer] (https://stackoverflow.com/a/9160009/3388225).

aleksxor
  • 7,535
  • 1
  • 22
  • 27