I've run into an issue with my logic I think. What should happen is, the user will enter an answer to the presented question. Once the question has been submitted, the current text (first question) disappears, and the next question in the array appears in place of the first question.
Currently the questions continue to pile on to one another without removing the previous question. Every time I try and add more code to remove the element, it gives me an error.
Please help! I am slowly adding to this codes functionality but I am stuck now on this add/remove text thing.
$(function() {
$("#submit").on("click", askQuestion)
var questions = [{
question: "Is the price higher or lower than $40.00?",
answer: "higher"
},
{
question: "Is the price higher or lower than $100.00?",
answer: "higher"
},
{
question: "Is the price higher or lower than $50.00?",
answer: "lower"
}
];
function askQuestion() {
if (answer && document.querySelector("#user-answer").value == answer) {
document.querySelector("#correct").style.display = "block";
document.querySelector("#sorry").style.display = "none";
answer = randomQuestion()
} else {
document.querySelector("#correct").style.display = "none";
document.querySelector("#sorry").style.display = "block";
}
}
function randomQuestion() {
var question = questions[Math.floor(Math.random() * questions.length)];
document.querySelector("#user-answer").value = "";
var element = document.createElement("div");
element.innerHTML = question.question;
$("#question").append(element.firstChild);
return question.answer;
}
var answer = randomQuestion();
});
<html>
<head>
<meta charset="UTF-8">
<title>Game time</title>
</head>
<body>
<h1>Question and Answer</h1>
<div>
<h2 id="question"></h2>
</div>
<label for="text">Answer:</label>
<input id="user-answer" type="text" value="">
<button id="submit" type="submit">Submit</button>
<p id="sorry" style="display: none">Sorry...</p>
<p id="correct" style="display: none">You got it!</p>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>