-2

The code I currently have is not working, and it seems to be because of the if statement as if I remove it, it works great, but then it doesn't do what I need, obviously.

What is wrong with this code?

<!DOCTYPE html>

<html>

<head>
  <title>Untitled Document</title>
</head>

<body>
  <input type="button" id="sample0" onclick="javascript:setval(0)" />
</body>

<script>
    var mysample = 0;

    function setval(varval) {
        mysample = varval;
        alert(mysample);
    }

    if (mysample = 0) {
        alert("GET OFF MY LAWN");
    }
</script>

<body>
    <marquee id="Marquee1">Hello</marquee>
</body>

</html>
Danziger
  • 19,628
  • 4
  • 53
  • 83
Ben Ice
  • 1
  • 2

3 Answers3

1

mysample = 0 is setting mysample to be 0 and then returning 0 so the if statement fails. You want to test equality which requires two or three = signs. Try if( mysample === 0 )

Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
1

The condition in your if statment in

Try

if(mysample === 0)

You can see this documentation on the use of logical operators in javascript.

0

This if(mysample = 0) will always return true and make mysample as 0. Use === to check.

yue you
  • 2,206
  • 1
  • 12
  • 29