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 be β€œOFF” and will not go 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 run: HP Netbook: Ubuntu Linux 10.04: Firefox for Ubuntu 1.0.

+6
javascript
source share
5 answers

Both of your if run one after the other when you change the value, and then immediately read it and change it:

 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 else in this case should stop.

+10
source share

Why do you pass the button if you are going to see it?

In addition, since you know the possible values, you only need to check if it is turned off, otherwise you know that it is turned on.

 // Toggles the passed button from OFF to ON and vice-versa. function toggle(button) { if (button.value == "OFF") { button.value = "ON"; } else { button.value = "OFF"; } } 

If you want to get fancy and save a couple of bytes, you can use the ternary operator:

 function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";} 
+13
source share

Why not use a switch?

 function toggle(button) { switch(button.value) { case "ON": button.value = "OFF"; break; case "OFF": button.value = "ON"; break; } } 
+1
source share

Another way to do this:

 var button = document.querySelector("button"); var body = document.querySelector("body"); var isOrange = true; button.addEventListener("click", function() { if(isOrange) { body.style.background = "orange"; }else { body.style.background = "none"; } isOrange = !isOrange; }); 

In a JavaScript file.

/ *****

ATTENTION! Another way is to apply the class to the element we want to change.

The CSS file must have a class with the desired format:

 .orange { background: orange; } 

In the latter case, in our js file, we only need to make a class application:

 var button = document.querySelector("button"); button.addEventListener("click", function() { document.body.classList.toggle("orange"); }); 

Yours faithfully:)

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

All Articles