TransWikia.com

Trying to make a magic eight ball and if the user does not enter a question it should say please ask a question but it does not work

Stack Overflow Asked by manusekhon983 on December 16, 2021

//Magic 8 ball

//Variables
let questionEl = document.getElementById("Question");
let magic8BallEl = document.getElementById("magic8ball");
let answerSpaceEl = document.getElementById("answerSpace");

//eventlistener 
magic8BallEl.addEventListener("click", giveAnswer)

function giveAnswer() {
  if(questionEl === ""){
    document.getElementById("answerSpace").innerHTML = " Please ask a question."
  }else {
  let randnum = Math.random();
   if (randnum < 0.2) {
    answerSpaceEl.innerHTML = " Without a doubt.";
  } else if (randnum < 0.4) {
    answerSpaceEl.innerHTML = " As I see it, yes.";
  } else if (randnum < 0.6) {
    answerSpaceEl.innerHTML = " Concentrate and ask again.";
  } else if (randnum < 0.8) {
    answerSpaceEl.innerHTML = " Don't count on it.";
  } else {
    answerSpaceEl.innerHTML = " Outlook not so good.";
  }
  }
}

When there is no input it should say please ask a question but it just skips it and pretends it doesn’t exist, how do I make this work?

2 Answers

document.getElementById() returns an element -- it will likely never be strictly-equal to an empty string. you should probably use questionEl.value === ""

Answered by nthall on December 16, 2021

questionEl cannot be equal to empty string. I don't know which element you are getting when querying Question but it won't be a string. maybe questionEl.innerHTML will help or questionEl.value

Answered by Evgeny Klimenchenko on December 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP