Skip to content
Advertisement

I am trying to make a simple toggle button in javascript

I am trying to make a simple toggle button in javascript. However, the button will only turn “OFF” and will not turn back “ON”

<html><head></head>
<script type="text/javascript">
function toggle(button)
{
  if(document.getElementById("1").value=="OFF"){
   document.getElementById("1").value="ON";}

  if(document.getElementById("1").value=="ON"){
   document.getElementById("1").value="OFF";}
}
</script>
<body>
<form action="">
<input type="button" id="1" value="ON" style="color:blue"
       onclick="toggle(this);">
</form></body></html>

I am running:HP Netbook : Ubuntu Linux 10.04 : Firefox for Ubuntu 1.0.

Advertisement

Answer

Both of your if statements are getting executed one after each other, as you change the value and then immediately read it again and change it back:

function toggle(button)
{
  if(document.getElementById("1").value=="OFF"){
   document.getElementById("1").value="ON";}

  else if(document.getElementById("1").value=="ON"){
   document.getElementById("1").value="OFF";}
}

Adding the else in there should stop this happening.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement