0

I'm new in javascript and in web programming on the whole. I'm trying to make script which will change image pic0.png depending on var lvl's value.

This is the script:

<!DOCTYPE html>
<html>
<body>

<script>
    var pic = "pic0.png";
</script>

<img id="myImg" src="pic0.png" width="107" height="98">
<p>Click the button to change the value of the src attribute of the image.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction() 
{
    var lvl = 2;
    if (lvl = 1)
    {
        pic = "pic1.png";
    }
    else if (lvl = 2)
    {
        pic = "pic2.jpg";
    }
    document.getElementById("myImg").src = pic;
}

</script>

</body>
</html>

When var lvl equals to 2, picture must change to pic2.jpg, but there is problem - after I click button 'try it!', the picture changes to pic1.png, no matter if var lvl equals 2 or 1.

Smittey
  • 2,475
  • 10
  • 28
  • 35

2 Answers2

2

You're assigning the value instead of checking. You need to use the double equal operator:

function myFunction() 
{
  var lvl = 2;
  if (lvl == 1)
  {
    pic = "pic1.png";
  }
  else if (lvl == 2)
  {
    pic = "pic2.jpg";
  }
  document.getElementById("myImg").src = pic;
}
Toothbrush
  • 2,080
  • 24
  • 33
jcubic
  • 61,973
  • 54
  • 229
  • 402
0

== or === should be used when comparing. = is an assignment operator.

if (lvl == 1)
{
pic = "pic1.png";
}
else if (lvl == 2)
{
pic = "pic2.jpg";
}
void
  • 36,090
  • 8
  • 62
  • 107