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" value="ON" onclick="toggle(this);"> </form></body></html> 

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

5 Answers

Why are you passing the button if you're going to look it up?

Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's 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 wanna get fancy and save a couple of bytes you can use the ternary operator:

function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";} 
0

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.

1

Another method to do this is:

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 the JavaScript file.

/*****

NOTE! Another way is applying a class to the element that we want to change.

The CSS file must have the class with the format we want:

.orange { background: orange; } 

By last in our js file we only need to make the application of the class:

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

Regards :)

Why not use a switch?

function toggle(button) { switch(button.value) { case "ON": button.value = "OFF"; break; case "OFF": button.value = "ON"; break; } } 
1
<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" value="ON" onclick="toggle(this);"> </form> </body> </html> 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy