Apology for the trouble. I am trying to learning on creating a simple Quiz. I am trying to get javascript to "listen" to the button’s value clicked, and if it is align with the answer, I want it to create a console.log("correct)".
I had been trying for multiple method to try to prompt an response including which is about creating a function to individually check if which button is clicked then prompt a response. However, i think this is not doable because once the first question is answered correctly, then i didn’t know how to proceed to make the supposedly "correct button" for question 2 to prompt the response. The "correct button" keep get stuck with the "correct button for question 1. Therefore, i am trying different approach which I am trying to get if the button’s value is align the answer then prompt a response.
const myTextArea = document.getElementById("question")
const btnGlobal = document.querySelectorAll("button")
const btnOne = document.getElementById("button-one")
const btnTwo = document.getElementById("button-two")
const btnThree = document.getElementById("button-three")
const btnFour = document.getElementById("button-four")
let questions = [{
question: "What did you eat today?",
choiceA: "Fried Noodle",
choiceB: "Chinese Dumpling",
choiceC: "Chicken Rice",
choiceD: "Pan Mee",
answer: "B",
},
{
question: "What did you drink today?",
choiceA: "Carbonate Drinks",
choiceB: "3 Layer Tea",
choiceC: "Coffee",
choiceD: "Milo",
answer: "D",
},
{
question: "What did you do today?",
choiceA: "Jogging",
choiceB: "Swimming",
choiceC: "Watching Movie",
choiceD: "Sleeping",
answer: "C",
}]
let currentQuestion = 0;
function ansCheck() {
var selectAns = questions[currentQuestion].answer
if (target.value == selectAns) {
console.log("correct");
} else {
console.log("wrong");
}
}
<div class="main-body">
<p id="question">Input your question here.</p>
<div class="btn-list">
<button class="button" onclick="ansCheck()" id="button-one" value="A" type="submit">Choice A</button>
<button class="button" onclick="ansCheck()" id="button-two" value="B" type="submit">Choice B</button>
<button class="button" onclick="ansCheck()" id="button-three" value="C" type="submit">Choice C</button>
<button class="button" onclick="ansCheck()" id="button-four" value="D" type="submit">Choice D</button>
</div>
2
Answers
first: change the html buttons this way:
then change the function:
Pass
this
into your inline click handlerretrieve the currently clicked target from your click event handler