The radio input elements needed some adjustments. To ensure better functionality, it is recommended to include a label element below each input with type="radio" and omit the closing radio tag.
To streamline the JavaScript code, you can simplify by verifying if only the right answer is selected. Below, I have provided a code snippet containing the script for reference.
By isolating only the correct answer input elements, you can store them in an array and iterate over the array to determine if the correct answer is chosen.
I have demonstrated an improved method to achieve the desired outcome with an example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Quiz Application</h1>
<h2>Score: <span id="score">0</span></h2>
<div>
<fieldset>Who is the founder of Pakistan? <br>
<input type="radio" name="founder" id="q1_o1" value="Allama Iqbal">
<label for="founder">Allama Iqbal</label>
<input type="radio" name="founder" id="q1_o2" value="Manzoor Kapri">
<label for="founder">Manzoor Kapri</label>
<input type="radio" name="founder" id="q1_o3" value="Quaid-e-Azam">
<label for="founder">Liaquat Ali Jinah</label>
<input type="radio" name="founder" id="q1_o4" value="Liaquat Ali Jinah">
<label for="founder">Liaquat Ali Jinah</label>
</fieldset>
<fieldset>Who is the national poet of Pakistan? <br>
<input type="radio" name="national_poet" id="q2_o1" value="Allama Iqbal">
<label for="national_poet">Allama Iqbal</label>
<input type="radio" name="national_poet" id="q2_o2" value="Manzoor Kapri">
<label for="national_poet">Manzoor Kapri</label>
<input type="radio" name="national_poet" id="q2_o3" value="Quaid-e-Azam">
<label for="national_poet">Liaquat Ali Jinah</label>
<input type="radio" name="national_poet" id="q2_o4" value="Liaquat Ali Jinah">
<label for="national_poet">Liaquat Ali Jinah</label>
</fieldset>
</div>
<button onClick="check()">Check Answer</button>
<script>
function check(){
// question no1
var score = 0;
var wrong_count = 0;
var scoreNode = document.getElementById('score');
const answer1 = document.getElementById('q1_o3');
const answer2 = document.getElementById('q2_o1');
const answers = [answer1, answer2];
answers.forEach(answer => {
if (answer.checked) {
score++
} else {
wrong_count++
}
})
scoreNode.innerHTML = score;
if (wrong_count > 0) {
alert(`You answered ${wrong_count} question(s) incorrectly.`);
}
}
</script>
</body>
</html>