Ad

How Can I Add A Picture Instead Of Text In An If Or Else Statement

- 1 answer

Hi I have created a HTML and JavaScript website with a conditional statement where it replies something back if you say hi.

function myFunction() {
    var letter = document.getElementById("myInput").value.toLowerCase(),
        text;

    if (letter === "hi im jack") {
        text = "Spot on! Good job!";
    } else if (letter === "hi" || letter === "hey" || letter === "hello" || letter === "hi there") {
        text = "Hi I Am Mike";
    }
    document.getElementById("demo").innerHTML = text;
}
<input id="myInput" type="text" onkeyup="myFunction()" style="font-size: 30pt; height: 50px; width: 600px;">
<button onclick="myFunction()" style="font-size: 30pt; height: 50px; width: 200px;">ENTER</button>
<p id="demo">result here</p>

The problem is I need to add an image instead of text for one of the replies. I also need to know how to make it send you to a different website automatically. I'm looking for something really simple that can replace the "text ==" if possible.

Ad

Answer

Use the same code as you used and assign new values to the text variable as follows:

function myFunction() {
var letter = document.getElementById("myInput").value.toLowerCase(),
    text;

if (letter === "hi im jack") {
    text = '<img src="imageName.jpg" width="200" height="200" />'; //Show an image
} else if (letter === "hi" || letter === "hey" || letter === "hello" || letter === "hi there") {
    location.href = 'http://www.websitename.com'; //Redirect automatically
}
document.getElementById("demo").innerHTML = text;

}

Ad
source: stackoverflow.com
Ad