Max R
Max R

Reputation: 109

How to change if statement from alert to text

How would I instead of have the if statement come up as an alert, have it appear as text on my page. Thanks

 document.getElementById("button").onclick=function() {

        if (document.getElementById("ask").value=="how tall are the pyramids") {

            alert ("146.5 meters");

            } else if (document.getElementById("ask").value == "how tall is the gateway arch") {

alert("630 feet");

         } else if (document.getElementById("ask").value == "how tall is the empire state building") {

         alert("6900 feet");

Upvotes: 2

Views: 75

Answers (3)

NewToJS
NewToJS

Reputation: 2772

You want to add another element to your page that can display the results.

In the demo below I have added a span element and set the id attribute to answer.

document.getElementById("button").onclick=function(){
var Q = document.getElementById("ask").value;
var A = document.getElementById("answer");
var Result = "Ask another?";
  if (Q=="how tall are the pyramids"){
    Result="146.5 meters";
  }else if(Q=="how tall is the gateway arch"){
    Result="630 feet";
  }else if(Q == "how tall is the empire state building"){
    Result="6900 feet";
  }
  A.innerHTML = Result;
}
<span id="answer"></span><br/>
<input type="text" id="ask" />
<button type="button" id="button">Ask</button>

If you don't understand any of the above source code, please leave a comment below.

I hope this helps. Happy coding!

Upvotes: 1

CollinD
CollinD

Reputation: 7573

I may have misunderstood, but it sounds like you want to display the value in an html element rather than alerting the value. See the below example

document.getElementById("button").onclick = function() {
  var val = document.getElementById("ask").value;
  var answer = "I don't know!";
  if (val == "how tall are the pyramids")
    answer = "146.5 meters";
  else if (val == "how tall is the gateway arch")
    answer = "630 feet";
  else if (val == "how tall is the empire state building")
    answer = "6900 feet";
  document.getElementById("answer").innerHTML = answer;
}

And in the html, add an answer element like so

<p id="answer"></p>

See CodePen

Upvotes: 1

Kishan
Kishan

Reputation: 1190

change

 document.getElementById("ask").value

to

document.getElementById("ask").innerHTML

or

document.getElementById("ask").innerText

Upvotes: 0

Related Questions