Daniel Fregoso Daniel Fregoso - 3 months ago 11
Javascript Question

How can I get answer on same page instead of an alert?

I want a button that every time you click it it gives you a different answer(Animals, Movies or TV Shows, and so on), the thing is I have a button (that I found online, I'm new at coding) but that button gives me the answer in a little alert box, is there a way to make it give me the answer below the button? Here's the code I found:

var words = ['Animals', 'Movies', 'TV Shows'];

function randomAlert() {


var alertIndex;


var randomValue = Math.random();


if (randomValue < 0.5) {
alertIndex = 0;
}


else if(randomValue < 0.8) {
alertIndex = 1;
}


else {
alertIndex = 2;
}

alert(words[alertIndex]).innerHTML
}

Answer

You can just get rid of the alert call and insert it into a div, span, h1, whatever. Here's an example out of the many ways:

var words = ['Animals', 'Movies', 'TV Shows'];

function randomSelect() {


  var index;


  var randomValue = Math.random();


  if (randomValue < 0.5) {
    index = 0;
  }


  else if(randomValue < 0.8) {
    index = 1;
  }


  else {
    index= 2;
  }

  document.getElementById('answer').innerText = words[index]; //Get's an element of id 'answer'
}

randomSelect(); //Executes function
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
    <div id="answer">
        //Answer is inserted into here
    </div>
</body>
</html>

The above get's an element of id answer and inserts it into the element's text. This is done by accessing the innerText attribute of the element, which returns the text of the element. I then reassign the value to the index. This is quite a simple way of doing it, and I cleaned up some of the names of functions, variables.