-2

I tried

function myFunction() {
  alert("hi")
  myvar == 1
}
var myvar = 0;
if (myvar == 1) {
  alert("you already clicked me!")
 }
<button onclick="myFunction()">hi</button>

but that did not work.

I want one to work for a game I am making in pure code. If you place a wall (hit the button) it will say wall placed. If you try to hit the button again, it will say wall already placed, because you can not place a wall inside of a wall.

Tamir Klein
  • 3,514
  • 1
  • 20
  • 38
c--
  • 9
  • 3
  • First, the `if (myvar == 1) { alert("you already clicked me!") }` needs to be within the function, or else it will be evaluated at load. Second, reread on how [operators work, especially `==`](https://stackoverflow.com/questions/11871616/in-javascript-vs) – Asons May 05 '19 at 19:00

2 Answers2

0

try this -

var myvar = 0;
function myFunction() {
  alert(myvar === 0 ? "hi" : "you already clicked me!")
  myvar = 1;
}

there was few errors in you code -

assignment was wrong (this was equality) -

myvar == 1

the second rule should be inside the function

if (myvar == 1) {
  alert("you already clicked me!")
 }
ofriman
  • 198
  • 1
  • 1
  • 9
0

You have to put the check for the variable value and the increasing of the variable inside of the function of course.

The line myvar == 1 itself will actually result in the boolean false and is not assigned to a variable, so it won't do anything.

var myvar = 0;

function myFunction() {
  if (myvar > 0) {
    alert("you already clicked me " + myvar + "x!")
  } else {
    alert("hi")
  }
  myvar = myvar + 1; // or myvar++;
}
<button onclick="myFunction()">hi</button>
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50