Making a true of false quiz. Everything seems to work except the function to change the text inside an element isnt working on click.
<main>
<h1>Test</h1>
<div class = "container">
<div id = "question">
</div>
</br>
<input class="button" id="btnTrue" type="button" value="true"/>
<input class="button" id="btnFlase" type="button" value="false"/>
</div>
</div>
</main>
function questionIndex() {
document.getElementById("question").innerHTML = question;
return console.log(currentItemIndex);
}
const questions = [
["questionOne", "false"],
["questionTwo", "true"],
["questionThree", "true"],
["questionFour", "false"]
];
let points = 0;
let currentItemIndex = 0;
let question = questions[currentItemIndex][0];
let answer = questions[currentItemIndex][1];
const btn = document.getElementsByClassName("button");
questionIndex();
btn.addEventListener('click', event => {
if (event.target.value === answer) {
console.log("Correct");
points++
currentItemIndex++;
console.log(points);
questionIndex();
} else {
console.log("Wrong");
currentItemIndex++;
console.log(points);
questionIndex();
}
}
);
Hi and welcome to the forum!
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>
) to add backticks around text.
See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).
Can you elaborate on what you mean by “not working on click”? Also, do you have your full code (including html)?
I am guessing your button elements do not have a value
attribute with the corresponding value you are attempting to compare in the click event callback functions.
I have included HTML in the code. Im attempting to run a function that will execute on the click of a button. So far I have tried creating an “addEventListener” to run the function and change a few variables, and i have attempted to place on “onclick” to the input.
As I suspected, the value you have specified for the value
attributes of the buttons is not the same as the value you are checking in the questions array’s 2nd element of a particular subarray. Remember that JavaScript is case-sensitive.
FYI - Instead of creating a duplicate function for each button’s click event callback function, create a single function (i.e. checkAnswer) and pass the function name for it instead. This will make your code more DRY (Do Not Repeat Yourself).
I have updated by code based on your suggestions and im still not getting the results i should be. On top of not being able to refresh my question with the function “questionIndex()” now my event listener is causing problems.