Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 544
CDeanMartin Avatar asked Jun 15 '10 18:06

CDeanMartin


People also ask

How do you make a toggle button in JavaScript?

We can toggle a button using conditional statements like if-else statement in JavaScript. We can toggle almost all the properties of an element like its value, class, id, and color in JavaScript. To change any property of an element, we need to get the element using its id or class.

What is toggle in JavaScript?

The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

What is toggle button How do you create it explain with example?

A toggle button allows the user to change a setting between two states. You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.

How do I make a text toggle button?

To add text to the toggle button, we just need to add another HTML element inside the toggle button and style it using CSS to make it look like a label. Again use pseudo-class to create labels that shows ON and OFF text depending on the state of the toggle switch.


1 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";}
like image 193
Ben S Avatar answered Nov 16 '22 00:11

Ben S