I am trying to make a simple toggle button in javascript

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";}

Leave a Comment