I'm having an issue where it's printing 2 of the same image on to the page. Can someone help me fix it? I've spent the past 2 hours working on it and it's due today. I have it so it prints to another page the results based on what choices you make.
<html>
<head>
<title>Spirit Animal Quiz</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="quiz.css">
<h1><div class="title">Spirit Animal Quiz</div></h1>
</head>
<body onLoad="start()">
<form>
<br> <br>
<div class= "questionsStyle">
<div class="question">1. How would you describe your skin?</div><br>
<div class="answer">
<input type="radio" name="q1" onClick="scorer(1,2)">Rough<br>
<input type="radio" name="q1" onClick="scorer(1,4)">Smooth<br>
<input type="radio" name="q1" onClick="scorer(1,3)">Both<br>
</div><br>
<div class="question">2. Which of these words best describes you?</div><br>
<div class="answer">
<input type="radio" name="q2" onClick="scorer(2,2)" >Introvert<br>
<input type="radio" name="q2" onClick="scorer(2,6)">Extrovert<br>
<input type="radio" name="q2" onClick="scorer(2,4)">In between<br>
</div><br>
<div class="question3">3. What's your favorite color?</div><br>
<div class="answer3">
<input type="radio" name="q3">Red<br>
<input type="radio" name="q3">Blue<br>
<input type="radio" name="q3">Green<br>
<input type="radio" name="q3">Yellow<br>
<input type="radio" name="q3">Pink<br>
<input type="radio" name="q3">Purple<br>
<input type="radio" name="q3">Orange<br>
<input type="radio" name="q3">Brown<br>
</div><br>
<div class="question">4. Which of the following best describes you?</div><br>
<div class="answer">
<input type="radio" name="q4" onClick="scorer(4,6)">Timid<br>
<input type="radio" name="q4" onClick="scorer(4,4)">Courageous<br>
<input type="radio" name="q4" onClick="scorer(4,2)">Tough<br>
<input type="radio" name="q4" onClick="scorer(4,8)">Cowardly<br>
</div><br>
<div class="question">5. Which of these do you prefer?</div><br>
<div class="answer">
<input type="radio" name="q5" onClick="scorer(5,4)">Peace and quiet<br>
<input type="radio" name="q5" onClick="scorer(5,6)">Noise and crowds<br>
</div><br>
<div class="question">6. Do you cook your own food?</div><br>
<div class="answer">
<input type="radio" name="q6" onClick="scorer(6,2)">Yes<br>
<input type="radio" name="q6" onClick="scorer(6,4)">No<br>
</div><br>
<div class="question"><br>7. Which would you describe yourself as</div><br>
<div class="answer">
<input type="radio" name="q7" onClick="scorer(7,6)">Patient<br>
<input type="radio" name="q7" onClick="scorer(7,8)">Impatient<br>
</div><br>
<input type="button" name="result" value="Find out your spirit animal." onClick="total()">
</div>
</form>
<script language="javascript">
//sets up an array for the answers that are given
var result = new Array(7);
function start() {
for(var i=0; i<7; i++) { result[i]=0; }
}
// Adds points together.
function total() {
score=0;
for (var i=0; i<7; i++) { score=score+result[i]; }
analyzer(score);
}
output = new Array();
output[0] = "You have a more tender personality and tend to like being around others or at least feel like there is someone around. Your spirit animal is the crowd-loving rabbit";
output[1] = "Your a bit skittish, but you tend to stick around unless something bothers you. You prefer groups, but occasionally tend to wander on your own. Your spirit animal is the timid and fun loving deer.";
output[2] = "You are capable of doing things on your own, but don't really have an issue when in a group. You can be a bit tough to work with at times, but you always do your part. Your spirit animal is the fierce and courageous wolf.";
output[3] = "You prefer being alone in peace and quiet. You are patient and willing to do your own work to get what you need. Your spirit animal is the tough and vicious alligator.";
output[4] = "I think you missed something"
output[5] = "Come on now, you didn't answer any questions."
img = new Array();
img[0] = new Image();
img[0].src = 'images/Rabbit.jpg';
img[1] = new Image();
img[1].src = 'images/Deer.jpg';
img[2] = new Image();
img[2].src = 'images/Wolf.jpg';
img[3] = new Image();
img[3].src = 'images/Alligator.jpg';
function analyzer (score) {
// use total to determine spirit animal
if (score > 35) { finish = 0;}
else { if (score > 30) { finish = 1;}
else { if(score > 24) { finish = 2;}
else { if(score > 15) { finish = 3;}
else { if(score > 1) { finish = 4; }
else { finish = 5; console.warn("Please answer the questions.");}
}
}
}
}
//Add the points into an array
display(output[finish])
display(img[finish])
}
function scorer(q, points) {
q=q-1;
result[q]=points
}
//ALERT RESULTS: Replace with page change if time feasible
function display(output) {
if (score > 35) {document.write(output); document.write('<img src="images/Rabbit.jpg">')}
else if (score > 30) {document.write(output); document.write('<img src="images/Deer.jpg">')}
else if(score > 24) {document.write(output); document.write('<img src="images/Wolf.jpg">')}
else if(score > 15) {document.write(output); document.write('<img src="images/Alligator.jpg">')}
}
CSS
h1 {font-size: 3em; margin: center; font-weight:5; background-color:
red;text-align: center; border-radius: 6px;}
body { background-color: white; padding: 10px;
font-family: 'Roboto', sans-serif; font-size: 20px;
position: relative
overflow: hidden;
color:white;
background: black;
padding: 20px;
}
#questionStyle .answer{
font-family: cursive;
}
Remove this
img = new Array();
img[0] = new Image();
img[0].src = 'images/Rabbit.jpg';
img[1] = new Image();
img[1].src = 'images/Deer.jpg';
img[2] = new Image();
img[2].src = 'images/Wolf.jpg';
img[3] = new Image();
img[3].src = 'images/Alligator.jpg';
Related
I want to build a simple and easy Javascript-based quiz application(remember simple and easy code not with advanced Javascript) I tried my best but I am stuck at this point everything is working fine except the result. I want to get results in a html tag using Javascript. Here is my code:
// Javascript (important I need a solution in this code)
function check(){
// question no1
var score = 0;
var q1WriteAnswer = document.getElementById('q1_o3');
var q1option1 = document.getElementById('q1_o1');
var q1option2 = document.getElementById('q1_o2');
var q1option4 = document.getElementById('q1_o4');
if (q1WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// question no2
var score = 0;
var q2WriteAnswer = document.getElementById('q2_o1');
var q2option1 = document.getElementById('q2_o2');
var q2option2 = document.getElementById('q2_o3');
var q2option4 = document.getElementById('q2_o4');
if (q2WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no3
var score = 0;
var q3WriteAnswer = document.getElementById('q3_o2');
var q3option1 = document.getElementById('q3_o1');
var q3option2 = document.getElementById('q3_o3');
var q3option4 = document.getElementById('q3_o4');
if (q3WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no4
var score = 0;
var q4WriteAnswer = document.getElementById('q4_o4');
var q4option1 = document.getElementById('q4_o1');
var q4option2 = document.getElementById('q4_o2');
var q4option4 = document.getElementById('q4_o3');
if (q4WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no5
var score = 0;
var q5WriteAnswer = document.getElementById('q5_o1');
var q5option1 = document.getElementById('q5_o2');
var q5option2 = document.getElementById('q5_o3');
var q5option4 = document.getElementById('q5_o4');
if (q5WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no6
var score = 0;
var q6WriteAnswer = document.getElementById('q6_o1');
var q6option1 = document.getElementById('q6_o2');
var q6option2 = document.getElementById('q6_o3');
var q6option4 = document.getElementById('q6_o4');
if (q6WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Questiton No7
var score = 0;
var q7WriteAnswer = document.getElementById('q7_o1');
var q7option1 = document.getElementById('q7_o2');
var q7option2 = document.getElementById('q7_o3');
var q7option4 = document.getElementById('q7_o4');
if (q7WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no 8
var score = 0;
var q8WriteAnswer = document.getElementById('q8_o1');
var q8option1 = document.getElementById('q8_o2');
var q8option2 = document.getElementById('q8_o3');
var q8option4 = document.getElementById('q8_o4');
if (q8WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No9
var score = 0;
var q9WriteAnswer = document.getElementById('q9_o3');
var q9option1 = document.getElementById('q9_o1');
var q9option2 = document.getElementById('q9_o2');
var q9option4 = document.getElementById('q9_o4');
if (q9WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No10
var score = 0;
var q10WriteAnswer = document.getElementById('q10_o1');
var q10option1 = document.getElementById('q10_o2');
var q10option2 = document.getElementById('q10_o3');
var q10option4 = document.getElementById('q10_o4');
if (q10WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
var ab = document.createElement("h3");
ab.innerText = score;
document.body.appendChild(ab);
}
/* *{
padding: 0px;
margin: 0px;
} */
body{
color: white;
background-color: #222;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
fieldset{
border-radius: 15px;
text-align: center;
}
h3{
background-color: cornsilk;
color: blue;
width: 10vw;
height: 5vh;
text-align: center;
position: relative;
left: 45%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Quiz Application</h1>
<div>
<fieldset>
<p>Who is the founder of Pakistan?</p>
<input type="radio" name="founder" id="q1_o1">Allama Iqbal</radio>
<input type="radio" name="founder" id="q1_o2">Manzoor Kapri</radio>
<input type="radio" name="founder" id="q1_o3">Quaid-e-Azam</radio>
<input type="radio" name="founder" id="q1_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is national poet of Pakistan?</p>
<input type="radio" name="national_poet" id="q2_o1">Allama Iqbal</radio>
<input type="radio" name="national_poet" id="q2_o2">Manzoor Kapri</radio>
<input type="radio" name="national_poet" id="q2_o3">Quaid-e-Azam</radio>
<input type="radio" name="national_poet" id="q2_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the writer of national anthem of Pakistan?</p>
<input type="radio" name="anthem_poet" id="q3_o1">Allama Iqbal</radio>
<input type="radio" name="anthem_poet" id="q3_o2">Hafiz Jalindheri</radio>
<input type="radio" name="anthem_poet" id="q3_o3">Quaid-e-Azam</radio>
<input type="radio" name="anthem_poet" id="q3_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the national animal of Pakistan?</p>
<input type="radio" name="national_animal" id="q4_o1">Peacock</radio>
<input type="radio" name="national_animal" id="q4_o2">Dog</radio>
<input type="radio" name="national_animal" id="q4_o3">Lion</radio>
<input type="radio" name="national_animal" id="q4_o4">Markhor</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the Prime Minister of Pakistan?</p>
<input type="radio" name="pm" id="q5_o1">Imran Khan</radio>
<input type="radio" name="pm" id="q5_o2">Manzoor Kapri</radio>
<input type="radio" name="pm" id="q5_o3">Quaid-e-Azam</radio>
<input type="radio" name="pm" id="q5_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the area of pakistan in square km?</p>
<input type="radio" name="pk_sq_km" id="q6_o1">1,96,096 sq km</radio>
<input type="radio" name="pk_sq_km" id="q6_o1">5,05,095 sq km</radio>
<input type="radio" name="pk_sq_km" id="q6_o1">7,96,096 sq km</radio>
<input type="radio" name="pk_sq_km" id="q6_o1">2,96,096 sq km</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first prime minister of Pakistan?</p>
<input type="radio" name="first_PM" id="q7_o1">Liaquat Ali</radio>
<input type="radio" name="first_PM" id="q7_o2">Zulfiqar Ali Bhutto</radio>
<input type="radio" name="first_PM" id="q7_o3">Quaid-e-Azam</radio>
<input type="radio" name="first_PM" id="q7_o4">Manzoor Kapri</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Which was the first capital of Pakistan?</p>
<input type="radio" name="first_Capital" id="q8_o1">Karachi</radio>
<input type="radio" name="first_Capital" id="q8_o2">Islamabad</radio>
<input type="radio" name="first_Capital" id="q8_o3">Hydrabad</radio>
<input type="radio" name="first_Capital" id="q8_o4">Quetta</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first woman prime minister of Pakistan?</p>
<input type="radio" name="first_womanPM" id="q9_o1">Shoukat Khanam</radio>
<input type="radio" name="first_womanPM" id="q9_o2">Shamshad Akhtar</radio>
<input type="radio" name="first_womanPM" id="q9_o3">Benazir Bhutto</radio>
<input type="radio" name="first_womanPM" id="q9_o4">Liaquat Ali Jinah</radio>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>which is the current capital of Pakistan?</p>
<input type="radio" name="founder" id="">Islamabad</radio>
<input type="radio" name="founder" id="">Karachi</radio>
<input type="radio" name="founder" id="">Hydrabad</radio>
<input type="radio" name="founder" id="">Lahore</radio>
</fieldset>
</div><br>
<br>
<br>
<button onclick="check()">Results</button>
<script src="app.js"></script>
</body>
</html>
It can be done easier using the querySelector an example:
// Javascript (important I need a solution in this code)
function checkQuestion(questionName, answerID) {
if(questionName == null || answerID == null) return;
const answer = document.getElementById(answerID);
const question = document.querySelector(`input[name="${questionName}"]:checked`);
if(answer == null || question == null) return;
return answer.id === question.id;
}
function updateScore(name, score, isCorrect) {
if(isCorrect == null) return score;
if(isCorrect) {
document.querySelectorAll(`input[name="${name}"]:not(:checked)`).forEach(input => input.disabled = true);
return score + 1;
}
else alert("wrong answer");
return score;
}
function check() {
let score = 0;
// question no1
const nameQ1 = 'founder'
const validQ1 = checkQuestion(nameQ1, 'q1_o3');
score = updateScore(nameQ1, score, validQ1);
// question no2
const nameQ2 = 'national_poet';
const validQ2 = checkQuestion(nameQ2, 'q2_o1');
score = updateScore(nameQ2, score, validQ2);
// question no3
const nameQ3 = 'anthem_poet'
const validQ3 = checkQuestion(nameQ3, 'q3_o2');
score = updateScore(nameQ3, score, validQ3);
// question no4
const nameQ4 = 'national_animal'
const validQ4 = checkQuestion(nameQ4, 'q4_o4');
score = updateScore(nameQ4, score, validQ4);
// question no5
const nameQ5 = 'pm';
const validQ5 = checkQuestion(nameQ5, 'q5_o1');
score = updateScore(nameQ5, score, validQ5);
// question no6
const nameQ6 = 'pk_sq_km'
const validQ6 = checkQuestion(nameQ6, 'q6_o1');
score = updateScore(nameQ6, score, validQ6);
// question no7
const nameQ7 = 'first_PM';
const validQ7 = checkQuestion(nameQ7, 'q7_o1');
score = updateScore(nameQ7, score, validQ7);
// question no8
const nameQ8 = 'first_Capital';
const validQ8 = checkQuestion(nameQ8, 'q8_o1');
score = updateScore(nameQ8, score, validQ8);
// question no9
const nameQ9 = 'first_womanPM';
const validQ9 = checkQuestion(nameQ9, 'q9_o3');
score = updateScore(nameQ9, score, validQ9);
// question no9
const nameQ10 = 'founder2';
const validQ10 = checkQuestion(nameQ10, 'q10_o1');
score = updateScore(nameQ10, score, validQ10);
//display result
const ab = document.querySelector('.ab') || ((e) => {
e.classList.add('ab');
document.body.appendChild(e)
return e;
})(document.createElement("h3"));
ab.innerText = score;
}
/* *{
padding: 0px;
margin: 0px;
} */
body{
margin: 1em;
color: white;
background-color: #222;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
fieldset{
border-radius: 15px;
text-align: center;
}
h3{
background-color: cornsilk;
color: blue;
width: 10vw;
height: 5vh;
text-align: center;
position: relative;
left: 45%;
}
input[type=radio]:disabled ~ label {
color: gray;
}
<h1>Quiz Application</h1>
<div>
<fieldset>
<p>Who is the founder of Pakistan?</p>
<input type="radio" name="founder" id="q1_o1"><label>Allama Iqbal</label>
<input type="radio" name="founder" id="q1_o2"><label>Manzoor Kapri</label>
<input type="radio" name="founder" id="q1_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="founder" id="q1_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is national poet of Pakistan?</p>
<input type="radio" name="national_poet" id="q2_o1"><label>Allama Iqbal</label>
<input type="radio" name="national_poet" id="q2_o2"><label>Manzoor Kapri</label>
<input type="radio" name="national_poet" id="q2_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="national_poet" id="q2_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the writer of national anthem of Pakistan?</p>
<input type="radio" name="anthem_poet" id="q3_o1"><label>Allama Iqbal</label>
<input type="radio" name="anthem_poet" id="q3_o2"><label>Hafiz Jalindheri</label>
<input type="radio" name="anthem_poet" id="q3_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="anthem_poet" id="q3_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the national animal of Pakistan?</p>
<input type="radio" name="national_animal" id="q4_o1"><label>Peacock</label>
<input type="radio" name="national_animal" id="q4_o2"><label>Dog</label>
<input type="radio" name="national_animal" id="<label>q4_o3"><label>Lion</label>
<input type="radio" name="national_animal" id="q4_o4"><label>Markhor</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the Prime Minister of Pakistan?</p>
<input type="radio" name="pm" id="q5_o1"><label>Imran Khan</label>
<input type="radio" name="pm" id="q5_o2"><label>Manzoor Kapri</label>
<input type="radio" name="pm" id="q5_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="pm" id="q5_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the area of pakistan in square km?</p>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>1,96,096 sq km</label>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>5,05,095 sq km</label>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>7,96,096 sq km</label>
<input type="radio" name="pk_sq_km" id="q6_o1"><label>2,96,096 sq km</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first prime minister of Pakistan?</p>
<input type="radio" name="first_PM" id="q7_o1"><label>Liaquat Ali</label>
<input type="radio" name="first_PM" id="q7_o2"><label>Zulfiqar Ali Bhutto</label>
<input type="radio" name="first_PM" id="q7_o3"><label>Quaid-e-Azam</label>
<input type="radio" name="first_PM" id="q7_o4"><label>Manzoor Kapri</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Which was the first capital of Pakistan?</p>
<input type="radio" name="first_Capital" id="q8_o1"><label>Karachi</label>
<input type="radio" name="first_Capital" id="q8_o2"><label>Islamabad</label>
<input type="radio" name="first_Capital" id="q8_o3"><label>Hydrabad</label>
<input type="radio" name="first_Capital" id="q8_o4"><label>Quetta</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first woman prime minister of Pakistan?</p>
<input type="radio" name="first_womanPM" id="q9_o1"><label>Shoukat Khanam</label>
<input type="radio" name="first_womanPM" id="q9_o2"><label>Shamshad Akhtar</label>
<input type="radio" name="first_womanPM" id="q9_o3"><label>Benazir Bhutto</label>
<input type="radio" name="first_womanPM" id="q9_o4"><label>Liaquat Ali Jinah</label>
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>which is the current capital of Pakistan?</p>
<input type="radio" name="founder2" id=""><label>Islamabad</label>
<input type="radio" name="founder2" id=""><label>Karachi</label>
<input type="radio" name="founder2" id=""><label>Hydrabad</label>
<input type="radio" name="founder2" id=""><label>Lahore</label>
</fieldset>
</div><br>
<br>
<br>
<button onclick="check()">Results</button>
The radio input elements were incorrect. You would want to add a label element beneath each input type="radio" and remove the closing radio tag.
You can then simplify your javascript by checking if only the correct answer is selected. I provided a code example with the script at the bottom.
By getting only the correct answer input elements, you can store them in an array and loop over the array to see if the correct answer is checked.
I provided an example to show a better way to get what you are looking for.
<!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>
you have a few mistakes:
you keep adding a closing < /radio > that shouldn't be there
you keep resetting sum to 0
you js has 10 questions your html has 9
your append to body is incorrect
// Javascript (important I need a solution in this code)
function check(){
// question no1
var score = 0;
var q1WriteAnswer = document.getElementById('q1_o3');
var q1option1 = document.getElementById('q1_o1');
var q1option2 = document.getElementById('q1_o2');
var q1option4 = document.getElementById('q1_o4');
if (q1WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// question no2
// var score = 0;
var q2WriteAnswer = document.getElementById('q2_o1');
var q2option1 = document.getElementById('q2_o2');
var q2option2 = document.getElementById('q2_o3');
var q2option4 = document.getElementById('q2_o4');
if (q2WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no3
// var score = 0;
var q3WriteAnswer = document.getElementById('q3_o2');
var q3option1 = document.getElementById('q3_o1');
var q3option2 = document.getElementById('q3_o3');
var q3option4 = document.getElementById('q3_o4');
if (q3WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no4
// var score = 0;
var q4WriteAnswer = document.getElementById('q4_o4');
var q4option1 = document.getElementById('q4_o1');
var q4option2 = document.getElementById('q4_o2');
var q4option4 = document.getElementById('q4_o3');
if (q4WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no5
// var score = 0;
var q5WriteAnswer = document.getElementById('q5_o1');
var q5option1 = document.getElementById('q5_o2');
var q5option2 = document.getElementById('q5_o3');
var q5option4 = document.getElementById('q5_o4');
if (q5WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no6
// var score = 0;
var q6WriteAnswer = document.getElementById('q6_o1');
var q6option1 = document.getElementById('q6_o2');
var q6option2 = document.getElementById('q6_o3');
var q6option4 = document.getElementById('q6_o4');
if (q6WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Questiton No7
// var score = 0;
var q7WriteAnswer = document.getElementById('q7_o1');
var q7option1 = document.getElementById('q7_o2');
var q7option2 = document.getElementById('q7_o3');
var q7option4 = document.getElementById('q7_o4');
if (q7WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question no 8
// var score = 0;
var q8WriteAnswer = document.getElementById('q8_o1');
var q8option1 = document.getElementById('q8_o2');
var q8option2 = document.getElementById('q8_o3');
var q8option4 = document.getElementById('q8_o4');
if (q8WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No9
// var score = 0;
var q9WriteAnswer = document.getElementById('q9_o3');
var q9option1 = document.getElementById('q9_o1');
var q9option2 = document.getElementById('q9_o2');
var q9option4 = document.getElementById('q9_o4');
if (q9WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
// Question No10
/*
var score = 0;
var q10WriteAnswer = document.getElementById('q10_o1');
var q10option1 = document.getElementById('q10_o2');
var q10option2 = document.getElementById('q10_o3');
var q10option4 = document.getElementById('q10_o4');
if (q10WriteAnswer.checked==true){
score++
}
else{
alert("wrong answer");
}
*/
var ab = document.createElement("h3");
ab.innerText = score;
document.getElementsByTagName('body')[0].appendChild(ab);
}
/* *{
padding: 0px;
margin: 0px;
} */
body{
color: white;
background-color: #222;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
background-size: cover;
background-position: center;
}
fieldset{
border-radius: 15px;
text-align: center;
}
h3{
background-color: cornsilk;
color: blue;
width: 10vw;
height: 5vh;
text-align: center;
position: relative;
left: 45%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Application</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Quiz Application</h1>
<div>
<fieldset>
<p>Who is the founder of Pakistan?</p>
<input type="radio" name="founder" id="q1_o1">Allama Iqbal
<input type="radio" name="founder" id="q1_o2">Manzoor Kapri
<input type="radio" name="founder" id="q1_o3">Quaid-e-Azam
<input type="radio" name="founder" id="q1_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is national poet of Pakistan?</p>
<input type="radio" name="national_poet" id="q2_o1">Allama Iqbal
<input type="radio" name="national_poet" id="q2_o2">Manzoor Kapri
<input type="radio" name="national_poet" id="q2_o3">Quaid-e-Azam
<input type="radio" name="national_poet" id="q2_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the writer of national anthem of Pakistan?</p>
<input type="radio" name="anthem_poet" id="q3_o1">Allama Iqbal
<input type="radio" name="anthem_poet" id="q3_o2">Hafiz Jalindheri
<input type="radio" name="anthem_poet" id="q3_o3">Quaid-e-Azam
<input type="radio" name="anthem_poet" id="q3_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the national animal of Pakistan?</p>
<input type="radio" name="national_animal" id="q4_o1">Peacock
<input type="radio" name="national_animal" id="q4_o2">Dog
<input type="radio" name="national_animal" id="q4_o3">Lion
<input type="radio" name="national_animal" id="q4_o4">Markhor
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the Prime Minister of Pakistan?</p>
<input type="radio" name="pm" id="q5_o1">Imran Khan
<input type="radio" name="pm" id="q5_o2">Manzoor Kapri
<input type="radio" name="pm" id="q5_o3">Quaid-e-Azam
<input type="radio" name="pm" id="q5_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>what is the area of pakistan in square km?</p>
<input type="radio" name="pk_sq_km" id="q6_o1">1,96,096 sq km
<input type="radio" name="pk_sq_km" id="q6_o1">5,05,095 sq km
<input type="radio" name="pk_sq_km" id="q6_o1">7,96,096 sq km
<input type="radio" name="pk_sq_km" id="q6_o1">2,96,096 sq km
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first prime minister of Pakistan?</p>
<input type="radio" name="first_PM" id="q7_o1">Liaquat Ali
<input type="radio" name="first_PM" id="q7_o2">Zulfiqar Ali Bhutto
<input type="radio" name="first_PM" id="q7_o3">Quaid-e-Azam
<input type="radio" name="first_PM" id="q7_o4">Manzoor Kapri
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Which was the first capital of Pakistan?</p>
<input type="radio" name="first_Capital" id="q8_o1">Karachi
<input type="radio" name="first_Capital" id="q8_o2">Islamabad
<input type="radio" name="first_Capital" id="q8_o3">Hydrabad
<input type="radio" name="first_Capital" id="q8_o4">Quetta
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>Who is the first woman prime minister of Pakistan?</p>
<input type="radio" name="first_womanPM" id="q9_o1">Shoukat Khanam
<input type="radio" name="first_womanPM" id="q9_o2">Shamshad Akhta
<input type="radio" name="first_womanPM" id="q9_o3">Benazir Bhutto
<input type="radio" name="first_womanPM" id="q9_o4">Liaquat Ali Jinah
</fieldset>
</div><br>
<br>
<br>
<div>
<fieldset>
<p>which is the current capital of Pakistan?</p>
<input type="radio" name="founder" id="">Islamabad
<input type="radio" name="founder" id="">Karachi
<input type="radio" name="founder" id="">Hydrabad
<input type="radio" name="founder" id="">Lahore
</fieldset>
</div><br>
<br>
<br>
<button onclick="check()">Results</button>
<script src="app.js"></script>
</body>
</html>
Below is the code of a sample radio button quiz where multiple radio buttons are provided. Correct answers and wrong answers are defined in the code. User may check any answer or keep all blank. If user checks any radio button and finally clicks "Grade Me" button, label text of radio button of any wrong answers checked by the user shall appear as red and at the same time correct answer of that particular question shall appear in green (This will help the user know which question he answered wrong and what is its correct answer). I have tried several steps and searched many forums and failed. I think it will be really simple.
Example:
var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
answers[0] = "doesn't like";
answers[1] = "don't come";
answers[2] = "come";
var wrong = new Array(3);
wrong[0] = "don't like";
wrong[1] = "doesn't come";
wrong[2] = "comes";
var wrong1 = new Array(3);
wrong1[0] = "doesn't likes";
wrong1[1] = "doesn't comes";
wrong1[2] = "coming";
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < numQues; i++) {
currElt = i * numChoi;
answered = false;
for (j = 0; j < numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
answered = true;
if (currSelection.value == answers[i]) {
score += 3;
break;
}
if (currSelection.value == wrong[i]) {
score -= 1;
break;
}
if (currSelection.value == wrong1[i]) {
score -= 1;
break;
}
}
}
}
var scoreper = Math.round(score * 100 / 9);
form.percentage.value = scoreper + "%";
form.mark.value = score;
}
<title>Quiz Questions And Answers</title>
<center>
<h1>Quiz Questions</h1>
</center>
<p>
<form name="quiz">
<p>
<b><br>1. He -------------------- it.<br></b>
<label><input type="radio" name="q1" value="don't like">don't like</label><br>
<label><input type="radio" name="q1" value="doesn't like">doesn't like</label><br>
<label><input type="radio" name="q1" value="doesn't likes">doesn't likes</label><br>
<p><b>
<hr>
<br>2. They -------------------- here very often.<br></b>
<label><input type="radio" name="q2" value="don't come">don't come</label><br>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label><br>
<p><b>
<hr>
<br>3. John and Mary -------------------- twice a week.<br></b>
<label><input type="radio" name="q3" value="come">come</label><br>
<label><input type="radio" name="q3" value="comes">comes</label><br>
<label><input type="radio" name="q3" value="coming">coming</label>
<br>
<p><b>
<hr>
<p><b>
<input type="button"value="Grade Me"onClick="getScore(this.form);">
<input type="reset" value="Clear"><p>
Number of score out of 15 = <input type= text size 15 name= "mark">
Score in percentage = <input type=text size=15 name="percentage"><br>
</form>
<p>
<form method="post" name="Form" onsubmit="" action="">
</form>
Here is a rewrite of your code.
I fixed the illegal HTML and used best practices with event listeners, querySelectors and CSS
Please study the code and see if you understand. I can add more comments if needed
var answers = ["doesn't like","don't come","come"];
var rads, quiz; // need to be set after load
window.addEventListener("load",function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click",function(e) { // on click of scoreme
var score = 0;
for (var i=0;i<rads.length;i++) { // loop over all radios in the form
var rad = rads[i];
var idx = rad.name.substring(1)-1; //remove the q from the name - JS arrays start at 0
var checked = rad.checked;
var correct = rad.value==answers[idx];
if (correct) {
rad.closest("label").classList.toggle("correct");
if (checked) score +=3;
}
else if (checked) {
score--;
rad.closest("label").classList.toggle("error")
}
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
.correct {
color: green
}
.error {
color: red
}
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/>
Number of score out of 15 = <input type="text" size="15" id="mark">
Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
In your getScore function, when you find out that a certain element has a correct answer selected (whichever var is the label - unless you are using a custom radio button which I would recommend since changing the background of the label element would simply highlight the words), you can give it a new class using JS.
currSelection.classList.add("correct");
or
currSelection.classList.add("incorrect");
Then in your CSS file you can have rules saying
.correct { background: green !important; }
.incorrect { background: red !important; }
WoW!....Close....Thanks for support. But still all the wrong answers are showing red color. This will let the user know which question he answered wrong. That part is Okay. But once the wrong answers are marked with red(I mean only the wrongly selected radio button choice texts and not the entire question and answer choices
the correct answer of that wrong attempt to be shown in green to enlighten the user. And the sad part is that I again failed with the CSS thing. I wanted to create a quiz in blog and added custom CSS with conditional tag in html of blogger post.....Not Working. However, I will add the modified code here so that you get a clear picture if I am doing rightly as you said.(How and where to add the CSS rules inside this code(if that is what you mean))
var answers = ["doesn't like", "don't come", "come"];
var rads, quiz; // need to be set after load
window.addEventListener("load", function() { // when page loads
quiz = document.getElementById("quiz");
rads = quiz.querySelectorAll("input[type=radio]"); // all radios in the quiz
document.getElementById("scoreButton").addEventListener("click", function(e) { // on submit
var score = 0;
var checked = quiz.querySelectorAll("input[type=radio]:checked"); // all checked radios
for (var i = 0; i < checked.length; i++) { // loop over all checked radios in the form
var idx = checked[i].name.substring(1) - 1; //remove the q from the name - JS arrays start at 0
var correct = checked[i].value == answers[idx];
checked[i].closest("p").classList.toggle("error", !correct)
checked[i].closest("p").classList.toggle("correct", correct)
score += correct ? 3 : -1; // this is called a ternary
}
var scoreper = Math.round(score * 100 / rads.length);
document.querySelector("#percentage").innerHTML = scoreper + "%";
quiz.mark.value = score;
});
});
<!DOCTYPE HTML>
<html>
<body>
<title>Quiz Questions And Answers</title>
<div class="header">
<h1>Quiz Questions</h1>
</div>
<form id="quiz">
<div class="questions">
<p>
<b>1. He -------------------- it.</b><br/>
<label><input type="radio" name="q1" value="don't like" />don't like</label><br/>
<label><input type="radio" name="q1" value="doesn't https://stackoverflow.com/questions/53818896/change-label-text-of-all-radio-button-in-quiz-as-red-and-green/59801712#like" />doesn't like</label><br/>
<label><input type="radio" name="q1" value="doesn't likes" />doesn't likes</label>
</p>
<hr>
<p><b>2. They -------------------- here very often.</b><br/>
<label><input type="radio" name="q2" value="don't come">don't come</label><br/>
<label><input type="radio" name="q2" value="doesn't come">doesn't come</label><br/>
<label><input type="radio" name="q2" value="doesn't comes">doesn't comes</label>
</p>
<hr>
<p><b>3. John and Mary -------------------- twice a week.</b><br/>
<label><input type="radio" name="q3" value="come">come</label><br/>
<label><input type="radio" name="q3" value="comes">comes</label><br/>
<label><input type="radio" name="q3" value="coming">coming</label><br/>
</p>
<hr>
<p>
<input type="button" value="Grade Me" id="scoreButton">
<input type="reset" value="Clear"><br/> Number of score out of 15 = <input type="text" size="15" id="mark"> Score in percentage = <span id="percentage"></span>
<p>
</div>
</form>
</body>
</html>
You can try this:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var coffee = document.forms[0];
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
document.getElementById("score"+i).style.color = "green";
document.getElementById("order").value = "You Clicked Option " + i;
}
} }
</script>
</head>
<body>
<div id="score1" style="font-size: 50px">1</div>
<div id="score2" style="font-size: 50px">2</div>
<div id="score3" style="font-size: 50px">3</div>
<div id="score4" style="font-size: 50px">4</div>
**<form action="/action_page.php">
<input type="text" id="order" size="50">
<br>
<input type="radio" name="coffee" value="1" onclick="myFunction()">Option 1<br>
<input type="radio" name="coffee" value="2" onclick="myFunction()">Option 2<br>
<input type="radio" name="coffee" value="3" onclick="myFunction()">Option 3<br>
<input type="radio" name="coffee" value="4" onclick="myFunction()">Option 4<br>
</form>**
</body>
</html>
I was able to create a quiz using javascript and html. It is a simple quiz with 5 questions, for now only the solution for question one appears when the user is wrong, I tried adding a function for the other questions but it wont run, I want to find out how do i loop through all the five question to give solution at the bottom of every wrong answer given by the user.
<HEAD>
<style type="text/css">
<!--
.bgclr {background-color: white; color: black; font-weight: bold;}
-->
.hidden {
display: none;
}
.visible {
display: block;
}
</style>
<script language="JavaScript">
// Insert scooter questions number of questions
var numQues = 5;
// Insert number of choices in each question
var numChoi = 3;
// Insert number of questions displayed in answer area
var answers = new Array(5);
// Insert answers to questions
answers[0] = "Keep to the left side of the road far as is safe.";
answers[1] = "Road which cross.";
answers[2] = "When a traffic officer order you to do so.";
answers[3] = "Traffic circle where right of way is applicable.";
answers[4] = "(i), (ii) and (iii)";
answers[5] = "A marked pedestrian crossing ahead.";
function getScore(form) {
showCorrectAnswers();
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
function showCorrectAnswers() {
var q1Inputs = document.querySelectorAll('.q1-inputs input');
var correctAnswer = document.querySelector('.q1-inputs span');
var correct = correctAnswer.textContent;
q1Inputs.forEach(function(element) {
if (element.checked) {
if (element.value !== correct) {
correctAnswer.classList.remove('hidden');
} else {
correctAnswer.classList.add('hidden');
}
}
});
}
// End -->
</script>
</HEAD>
<!-- STEP TWO: Copy this code into the BODY of your HTML document -->
<BODY>
<h3>Scooter quiz by johnson</h3>
<form name="quiz">
1. Which rule is considered the most important RULE OF THE ROAD in South Africa?
<ul class="q1-inputs" style="margin-top: 1pt">
<li><input type="radio" name="q1" value="Always be courteous and considerate towards fellow road users.">Always be courteous and considerate towards fellow road users.</li>
<li><input type="radio" name="q1" value="Do not exceed the speed limit.">Do not exceed the speed limit.</li>
<li><input type="radio" name="q1" value="Keep to the left side of the road far as is safe.">Keep to the left side of the road far as is safe.</li>
<span class="hidden" style="color:red;">Keep to the left side of the road far as is safe.</span>
</ul>
2. Sign L9 warns you about... ahead.
<ul style="margin-top: 1pt">
<li><input type="radio" name="q2" value="Where you are also not allowed to park."> Where you are also not allowed to park..</li>
<li><input type="radio" name="q2" value="A railway crossing">A railway crossing</li>
<li><input type="radio" name="q2" value="Road which cross">Road which cross</li>
</ul>
3.Under what circumstances, if any, are you allowed to drive your motor motor vehicle on the right-hand side of a public road with traffic moving in both directions?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q3" value="When you switch the emergency lights of your vehicle on.">When you switch the emergency lights of your vehicle on.</li>
<li><input type="radio" name="q3" value="When a traffic officer order you to do so.">When a traffic officer order you to do so.</li>
<li><input type="radio" name="q3" value="Under no circumstance.">Under no circumstance.</li>
</ul>
4.Sign CC9 is found at ..
<ul style="margin-top: 1pt">
<li><input type="radio" name="q4" value="Traffic circle where right of way is applicable.">Traffic circle where right of way is applicable.</li>
<li><input type="radio" name="q4" value="Dangerous place where roadwork is being done.">Dangerous place where roadwork is being done.</li>
<li><input type="radio" name="q4" value="Sharp curve to the right.">Sharp curve to the right.</li>
</ul>
5.You may not obtain a learner’s license if...
<ul style="margin-top: 1pt">
<li><input type="radio" name="q5" value="A first-aid post."> A first-aid post.</li>
<li><input type="radio" name="q5" value="A railway crossing">A railway crossing</li>
<li><input type="radio" name="q5" value="Road which cross">Road which cross</li>
</ul>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear answers">
<p> Score = <strong><input class="bgclr" type="text" size="5" name="percentage" disabled></strong><br><br>
Correct answers:<br>
<textarea class="bgclr" name="solutions" wrap="virtual" rows="10" cols="100" disabled>
</textarea>
</form>
JavaScript update
var getScoreButton = document.getElementById("getScore"),
quizSections = document.getElementById("quizForm").querySelectorAll("ul"),
quizScore = document.getElementById("percentage"),
quizSolutions = document.getElementById("solutions"),
answers = new Array(5),
score = 0,
solutions = '';
// Insert answers to questions
answers[0] = "Keep to the left side of the road far as is safe.";
answers[1] = "Road which cross.";
answers[2] = "When a traffic officer order you to do so.";
answers[3] = "Traffic circle where right of way is applicable.";
answers[4] = "(i), (ii) and (iii)";
answers[5] = "A marked pedestrian crossing ahead.";
function checkAnswers(source) {
source.forEach(function(section, index){
var selectedAnswer = section.querySelector("input:checked");
if(selectedAnswer){
if(answers[index] === selectedAnswer.value){
score+=1;
}else{
solutions+= (index+1) + '. ' + answers[index] + "\n";
}
}else{
solutions+= (index+1) + '. ' + answers[index] + "\n";
}
});
quizScore.value = score;
quizSolutions.value = solutions;
score = 0;
solutions = '';
}
getScoreButton.addEventListener("click", function(){
checkAnswers(quizSections);
});
HTML update (added some id's)
<input type="button" value="Get score" id="getScore">
<input type="reset" value="Clear answers">
<p> Score = <strong><input class="bgclr" type="text" size="5" name="percentage" id="percentage" disabled></strong><br><br>
Correct answers:<br>
<textarea class="bgclr" name="solutions" id="solutions" wrap="virtual" rows="10" cols="100" disabled>
You can use .getAttribute('value') instesd of .value
UPDATE
function showCorrectAnswers() {
var x = ['q1-inputs', 'q2-inputs','q3-inputs', 'q4-inputs', 'q5-inputs'];
for(value of x){
var q1Inputs = document.querySelectorAll('.'+value+' input');
var correctAnswer = document.querySelector('.'+value+' span');
var correct = correctAnswer.textContent;
q1Inputs.forEach(function(element) {
if (element.checked) {
if (element.getAttribute('value') !== correct) {
correctAnswer.classList.remove('hidden');
} else {
correctAnswer.classList.add('hidden');
}
}});
}
}
I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.
On clicking submit I want the score and the correct answers to be printed on a new page. Right now the score pops up on an alert box. How can this be done in HTML/JavaScript ?
The code for my quiz application is :
<html>
<head>
<title>Quizzer</title>
<style type="text/css">
body {
background:#E3E1DC;
font-size:16px;
font-family:Helvetica, Arial;
line-height:1.2em;
color:#222222;
}
pre {
font-family:Consolas, Courier;
font-size: 12px;
color:#444444;
line-height:12px;
margin-left:30px;
margin-top:-28px;
}
.instructions {
margin-left:25px;
}
.button {
margin-left:10px;
margin-bottom:120px;
width:200px;
height:50px;
}
.question {
background:#F1E6D4;
padding:15px;
margin:10px;
}
.odd {
background:#9F9694;
}
.wrong {
border-left:#BA3D49 5px solid;
padding-left:10px;
}
</style>
<script langauge="JavaScript">
// number of questions in the quiz, this must be set exactly
var totalQuestions = 5;
// arrays to store answers, and user submited answers.
var answers = new Array;
var userAnswers = new Array;
// quiz answers
answers[1] = "B";
answers[2] = "C";
answers[3] = "D";
answers[4] = "D";
answers[5] = "B";
// sets the users answer selection to the appropriate array element
// in the userAnswers array.
// questionNumber is the question div id as well as the userAnswers
// array element index to store the answer in.
// answerSelection is the value of the selected answer from a question
function SetAnswer(questionNumber, answerSelection) {
userAnswers[questionNumber] = answerSelection;
}
// applies the .wrong class styling to any question div that is incorrect
function MarkIncorrectQuestions() {
for(i = 1; i <= totalQuestions; i++) {
if(answers[i] != userAnswers[i]) {
document.getElementById(i).className += " wrong";
}
}
}
// counts the number of correct answers
// returns the number of correct answers
function GetScore() {
var score = 0;
for(i = 1; i <= totalQuestions; i++) {
if(userAnswers[i] == answers[i])
score++;
}
return score;
}
// sets classes for each question div to its default styling.
function ApplyDefaultQuestionStyles() {
for(i = 1; i <= totalQuestions; i++) {
if(i % 2 == 0) {
document.getElementById(i).className = "question";
}
else {
document.getElementById(i).className = "question odd";
}
}
}
// calls all appropriate functions in order to check answers and mark
// incorrect questions.
function CheckQuiz() {
ApplyDefaultQuestionStyles();
var totalQuestions = '5';
var score = GetScore();
MarkIncorrectQuestions();
alert("You scored: " + score + " out of " + totalQuestions + ".");
//document.write("<h1>hello</h1>");
}
function result(score,totalQuestions){
document.write("Score" +score);
}
</script>
</head>
<body onLoad="ApplyDefaultQuestionStyles()">
<div class="instructions">
<h1>The Movie Quiz</h1>
</div>
<form>
<div id="1">
<p><strong>Question 1</strong></p>
<p>Where does “It’s a Wonderful Life” take place?</p>
<p><input type="radio" value="A" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Hills</p>
<p><input type="radio" value="B" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Falls</p>
<p><input type="radio" value="C" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford Lake</p>
<p><input type="radio" value="D" onClick="SetAnswer(1, this.value)" name="radiobutton2">Bedford City</p>
</div>
<div id="2">
<p><strong>Question 2</strong></p>
<p>In “The Godfather,” who was murdered in the causeway?</p>
<p><input type="radio" value="A" onClick="SetAnswer(2, this.value)" name="radiobutton2">Luca Brasi</p>
<p><input type="radio" value="B" onClick="SetAnswer(2, this.value)" name="radiobutton2">Moe Greene</p>
<p><input type="radio" value="C" onClick="SetAnswer(2, this.value)" name="radiobutton2">Sonny</p>
<p><input type="radio" value="D" onClick="SetAnswer(2, this.value)" name="radiobutton2">Paulie</p>
</div>
<div id="3">
<p><strong>Question 3</strong></p>
<p>Where did Princess Leia hide the stolen plans for the Death Star?</p>
<p><input type="radio" value="A" onClick="SetAnswer(3, this.value)" name="radiobutton2">In C-3PO</p>
<p><input type="radio" value="B" onClick="SetAnswer(3, this.value)" name="radiobutton2">In a pocket in the hem of her white gown</p>
<p><input type="radio" value="C" onClick="SetAnswer(3, this.value)" name="radiobutton2">In the Millennium Falcon</p>
<p><input type="radio" value="D" onClick="SetAnswer(3, this.value)" name="radiobutton2">In R2-D2</p>
</div>
<div id="4">
<p><strong>Question 4</strong></p>
<p>In which of the following films did Robert Duvall NOT appear?</p>
<p><input type="radio" value="A" onClick="SetAnswer(4, this.value)" name="radiobutton2">To Kill a Mockingbird</p>
<p><input type="radio" value="B" onClick="SetAnswer(4, this.value)" name="radiobutton2">The Godfather</p>
<p><input type="radio" value="C" onClick="SetAnswer(4, this.value)" name="radiobutton2">Tender Mercies</p>
<p><input type="radio" value="D" onClick="SetAnswer(4, this.value)" name="radiobutton2">One Flew Over the Cuckoo’s Nest</p>
</div>
<div id="5">
<p><strong>Question 5</strong></p>
<p>Who was Scarlett O’Hara’s second husband?</p>
<p><input type="radio" value="A" onClick="SetAnswer(5, this.value)" name="radiobutton2">Frank Kennedy</p>
<p><input type="radio" value="B" onClick="SetAnswer(5, this.value)" name="radiobutton2">Rhett Butler</p>
<p><input type="radio" value="C" onClick="SetAnswer(5, this.value)" name="radiobutton2">Ashley Wilkes</p>
<p><input type="radio" value="D" onClick="SetAnswer(5, this.value)" name="radiobutton2">Charles Hamilton</p>
</div>
<p>
<input type="submit" class="ui-button" onClick="CheckQuiz()" value="Submit Answers" name="submitButton" class="button"></p>
</form>
</body>
You have two options instead of using an alert ...
1) Create a layered popup that pops up in front of all your page content (you could darken the BG as well like most modals do). This would allow you to pop the message up in the same page and not require the user to open another window.
2) Your other option would be to popup a new window and use javascript to write the information to that window. See the following link for more information on this: http://www.electrictoolbox.com/write-content-dynamic-javascript-popup/
I personally would go with the first because it guarantees that it will work even if the user has a popup blocker.