Is there a way to change the source of an HTML image using javascript based on variables? I am thinking of something like this:
var image = 1;
if(image=1) {
document.getElementById('myImage').src = "images/one.png";
} else if(image=2) {
document.getElementById('myImage').src = "images/two.png";
} else {
window.alert("You have a weird variable value");
}
Please tell me how I can get this to work using an if…then or switch statement.
=is an assignment. An assignment statement evaluates as itself. Soif(image=1)means “assign 1 to image, then if 1 is true…”. (1is always a true value).To compare two values use
===(or==if you want type munging).and