I am facing a challenge with a basic exercise I am working on. The exercise involves allowing visitors to ask a random question, and in return, they receive a random answer from an array.
I wish to retain the questions and their corresponding answers. I want the previous questions and answers to remain visible even after a new question is asked. Each new question and answer should appear below the previous ones (unless the visitor refreshes the page). Currently, the previous content disappears when a new question is asked. How can I achieve this, and where should I make the necessary code changes?
index.html:
<div id="title">
<h1>Get to know the future of your life in a <span>highly reliable way*</span></h1>
<h2>Ask your question below <i class="arrow down"></i> </h1>
</div>
<div id="mydiv">
<input type="text" id="myinput" placeholder="What question do you want to ask?">
<button id="button" type="mybutton">START THE PREDICTION</button>
<div id="myprediction"></div>
</div>
<h3 id="legal">*We are not responsible for inaccurate predictions.</h3>
script.js:
let button = document.querySelector("button");
let input = document.querySelector("input");
let prediction = ["Things don't look great for you.", "Don't worry, things will turn out fine.", "We're unsure about this outcome. Take control and make it happen.", "Take action before it's too late.", "Sometimes you need a break, then you can handle this.", "This might not work out."];
function predictor() {
if (input.value !== "") {
let randomNumber = Math.floor(Math.random() * prediction.length);
let currentPrediction = document.getElementById("myprediction").innerHTML;
document.getElementById("myprediction").innerHTML = currentPrediction + "<br>" + prediction[randomNumber];
}
}
button.addEventListener("click", predictor);