0

I need to create a button that works like this :

var i = true

first click --> var i = false
second click --> var i = true
....

HTML

 <input type="button" value="test" onclick="stop(); start();" />

How can i specify theese functions in my JS document ?

  • 1
    [Toggle a boolean in javascript](https://stackoverflow.com/questions/11604409/toggle-a-boolean-in-javascript) – Turnip Mar 29 '18 at 08:54

5 Answers5

1

you can toggle a boolean by doing this :

var b = true;
b = !b

in your case use :

<input type="button" value="test" onclick="b = !b;" />

it's better to doing this with a function

var b = true;
function toggle () { b = !b; console.log(b) }

and in your html

<input type="button" value="test" onclick="toggle();" />
Julien Amblard
  • 121
  • 1
  • 3
0

make a counter for clicks

var countClick= 0

if (countClick== 1) {
        //do the first click code
    }
    if (countClick== 2) {
        //do the second click code
    }
0

You can do it like this

<input type="button" value="test" />

And the javascript code.

var btn = document.getElementsByTagName('input')[0];
var i = true;

btn.addEventListener('click', function() {
    if (i == true)
        i = false;
    else
        i = true;
});
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
0

You can simply associate a function call on onclick event and then toggle the boolean value:

var i = true;
function clicked () {
  //toggle the value
  i = !i; 
  console.log(i);
}
<input type="button" value="test" onclick="clicked();" />
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Here is a snippet that does what you want. You can have it toggle forever or just the one time like your example.

var buttonClicks = 0;
var boolValue = true;
var boolValueOutput = document.getElementById("boolValue")

boolValueOutput.innerHTML = boolValue;

function onButtonClick()
{
  buttonClicks++;

  // If you want it to only work once uncomment this
  //if (buttonClicks > 2)
  //  return;
  
  boolValue = !boolValue;
  boolValueOutput.innerHTML = boolValue;
}
<input type="button" value="test" onclick="onButtonClick();" />
<p id="boolValue"></p>