So I wrote a code where there are 5 true/false questions and after clicking on the check button, the program shows whether your answer was in/correct by making the question box red or green and displays your score.
But after the click, it should also display each justification below the true/false buttons which is in questions
as justif
. I have written <p id = "just${(index+1)}"></p>
so that I can display justifications by index easily, but I don’t quite get how to do so
I have tried with getElementById
and insertAdjacentHTML
but no luck, can somebody tell me how to write that part of the code?
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Template</title>
<link rel="stylesheet" href="style.css">
<script>
let questions = [{
"quest": "'Visibility' is CSS property that specifies the transparency",
"ans": false,
"justif": "'Opacity' is used to specify the transparency of an element whereas 'visibility' specifies if element is visible "
}, {
"quest": "HTML elements can have 'id' and 'class' at the same time",
"ans": true,
"justif": "Any HTML element can have both of them together"
}, {
"quest": "DIV technically stands for Container",
"ans": false,
"justif": "DIV stands for Division"
}, {
"quest": "Padding can be negative",
"ans": false,
"justif": "Values for padding values can only be positive or zero"
}, {
"quest": "'text-shadow' is the CSS property which adds shadows to the text",
"ans": true,
"justif": "The CSS 'text-shadow' is used to add shadows to the text"
}];
console.log(questions[0].quest);
</script>
</head>
<body>
<section id="main">
</section>
<p id="score"></p>
<button type="button" onclick="checkAnswers()"><b>Check</b></button>
<script>
let i = 1;
questions.forEach(function(item, index) {
let HTMLcode = `<form id="id${(index+1)}">
<p>${item.quest}</p>
<input type="radio" name = "q${(index+1)}" id="q${(index+1)}t" value="1">
<label class = "true" for="q${(index+1)}t">True</label>
<input type="radio" name = "q${(index+1)}" id="q${(index+1)}f" value="0">
<label class = "false" for="q${(index+1)}f">False</label>
<p id = "just${(index+1)}"></p>
</form>
`;
document.getElementById('main').insertAdjacentHTML('beforeend', HTMLcode);
i++;
});
function checkAnswers() {
let correctAnswered = 0;
document.querySelectorAll('input[type="radio"]:checked').forEach(function(radio) {
let radioId = parseInt(radio.id.substring(1));
let userAnswer = radio.id.substring(1).slice(-1);
let questionAnswer = questions[radioId - 1].ans;
let p = document.getElementById("id" + radioId);
if (userAnswer == 't' && questionAnswer == true ||
userAnswer == 'f' && questionAnswer == false) {
p.style.backgroundColor = 'rgba(34, 172, 0, 0.789)';
correctAnswered++;
} else {
p.style.backgroundColor = 'rgba(255, 0, 0, 0.789)';
}
});
let score = document.getElementById("score");
score.textContent = "Your Score is " + correctAnswered + " out of 5";
}
</script>
</body>
</html>