I´m making a quiz with javascript and I have encountered a problem with getting the answer from chosen checkbox. I have gotten the checkboxes to work so that you can only pick one answer. Reason for using checkboxes is just that I tried to use radioboxes and I didn´t get it to work that way either.
Currently my form looks like this:
<div id="vastausformi">
<form id="vastaukset">
<label for="a">A)</label>
<input type="checkbox" classname="box" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" />
<label for="b">B)</label>
<input type="checkbox" classname="box" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" />
<label for="c">C)</label>
<input type="checkbox" classname="box" id="Check3" value="Value1" onclick="selectOnlyThis(this.id)" />
<label for="d">D)</label>
<input type="checkbox" classname="box" id="Check4" value="Value1" onclick="selectOnlyThis(this.id)" />
</form>
</div>
Then i have javascript for a question:
let questions= {
question: "Which city is the capital of Sweden?",
vastaus:{
a: 'Stockholm',
b: 'Malmö',
c: 'Göteborg',
d: 'Helsingborg'
},
correctAnswer: 'a'
};
Then I have made a function that checks the users guess.
function checkGuess(){
let correctAnswer= questions.valueOf(oikeaVastaus);
let playerChoice= document.getElementsByClassName("box");
if(playerChoice===correctAnswer){
console.log("correct");
}
else{
console.log("wrong");
}
};
guessSubmit.addEventListener('click', checkGuess);
The checkGuess function doesn´t seem to get the "answer". I get it so that it says that the answer is correct (no matter which checkbox you choose) or that all the answers are wrong. I have tried to "retrieve" the information from the checkboxes with different ways with no luck. I can´t seem to get hold of that "correctAnswer". I have also tried to make one specific checkbox "the correct choice", so that everytime you choose it, it would be correct, but that doesn´t work either. So that checkGuess function is just one of the ways I have tried to do the checking. I have also tried to leave away the declaration of playerChoice and put the input straight to the if statement. I have also tried to
Reason to use those consolelogs are just the see if the script works, so in the future the answer will be displayed on screen and there will be more questions than just one. I´m new to coding so I might be doing this compeletely wrong, but I wanted to make it so that one question appears and then there is four checkboxes to choose from, then there will be a button to get to next question.
I apologize for my english, but hopefully you will understand what I mean.
If anyone has any idea how to get this to work or have some alternative ways to do this, I would greatly appreciate it!
Aucun commentaire:
Enregistrer un commentaire