how to create an advanced html quiz [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been working on this quiz for days now. I have managed to create a quiz with solutions at the end, but I do not want that. I want the solutions to appear at the end of every wrong answer given by the user, and if the user is correct no answer should display,
<HEAD>
<style type="text/css">
<!--
.bgclr {background-color: white; color: black; font-weight: bold;}
-->
</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) {
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;
}
// 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 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>
</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>

Here I've shown you how this can be done for the first block of questions. You can work from there.
<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) {
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;
}
document.addEventListener('DOMContentLoaded', function() {
var q1Inputs = document.querySelector('.q1-inputs');
q1Inputs.addEventListener('change', function(event) {
if (event.target.value !== 'Keep to the left side of the road far as is safe.') {
q1Inputs.lastElementChild.classList.remove('hidden');
} else {
q1Inputs.lastElementChild.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>
<li class="hidden" style="color:red;">The correct answer is: Keep to the left side of the road far as is safe.</li>
</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>
UPDATE:
<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>

Related

How to display/indicate the right and wrong answers at the end of javascript quiz

as the title suggests I need help with how to display the right and wrong answers at the end of my javascript quiz. I've tried various ways and none seem to work. I've tried highlighting, writing next to and displaying underneath the score however nothing I try seems to work. Any guidance is greatly appreciated thanks x
var total_seconds = 30 * 1;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);
var timer;
function CheckTime() {
document.getElementById("quiz-time-left").innerHTML =
"Time Left: " + c_minutes + " minutes " + c_seconds + " seconds ";
if (total_seconds <= 0) {
score();
} else {
total_seconds = total_seconds - 1;
c_minutes = parseInt(total_seconds / 60);
c_seconds = parseInt(total_seconds % 60);
timer = setTimeout(CheckTime, 1000);
}
}
timer = setTimeout(CheckTime, 1000);
function highlightAnswerWithClass(question, answer, className) {
var answers = document.forms.form[question];
for (var index = 0; index < answers.length; index++) {
if (answers[index].value === answer) {
answers[index].classList.add(className);
}
}
}
function score() {
// stop timer
clearInterval(timer);
//Referencing the value of the questions
var q1 = document.forms.form.q1.value;
var q2 = document.forms.form.q2.value;
var q3 = document.forms.form.q3.value;
var q4 = document.forms.form.q4.value;
var q5 = document.forms.form.q5.value;
var q6 = document.forms.form.q6.value;
// disable form
var elements = document.getElementById("questions").elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
}
//Array for the questions
var questions = [q1, q2, q3, q4, q5, q6];
//Answers for each question
var answers = ["b", "b", "b", "b", "b", "b"];
//variable to keep track of the points
var points = 0;
var total = 6;
//max score
//Making use of a for loop to iterate over the questions and answers arrays
for (var i = 0; i < total; i++) {
if (questions[i] == answers[i]) {
points = points + 2; //Increment the score by 2 for every correct answer given
alert(points);
highlightAnswerWithClass(i + 2, questions[i], "correct");
} else {
points = points - 1;
alert(points);
highlightAnswerWithClass(i + 2, questions[i], "incorrect");
highlightAnswerWithClass(i + 2, answers[i], "correct");
}
}
//CSS for questions
if (points >= 4) {
document.body.style.backgroundColor = "rgba(0,255,0,0.2)";
} else {
document.body.style.backgroundColor = "rgba(255,0,0,0.1)";
}
var q = document.getElementById("p");
q.style.fontSize = "40px";
q.style.textAlign = "center";
q.innerHTML =
"You got " +
points +
" out of " +
total +
"<br />" +
"you used " +
(29 - Math.floor(total_seconds)) +
" seconds";
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body bgcolor="lightblue">
<div id="quiz-time-left"></div>
<form name="form" id="questions" onsubmit="return false;">
<h3>1. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q1" value="a" />a. 1<br />
<input type="radio" name="q1" value="b" />b. 2<br />
<input type="radio" name="q1" value="c" />c. 3<br />
<input type="radio" name="q1" value="d" />d. 4<br />
<h3>2. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q2" value="a" />a. 1<br />
<input type="radio" name="q2" value="b" />b. 2<br />
<input type="radio" name="q2" value="c" />c. 3<br />
<input type="radio" name="q2" value="d" />d. 4<br />
<h3>3. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q3" value="a" />a. 1<br />
<input type="radio" name="q3" value="b" />b. 2<br />
<input type="radio" name="q3" value="c" />c. 3<br />
<input type="radio" name="q3" value="d" />d. 4<br />
<h3>4. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q4" value="a" />a. 1<br />
<input type="radio" name="q4" value="b" />b. 2<br />
<input type="radio" name="q4" value="c" />c. 3<br />
<input type="radio" name="q4" value="d" />d. 4<br />
<h3>5. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q5" value="a" />a. 1<br />
<input type="radio" name="q5" value="b" />b. 2<br />
<input type="radio" name="q5" value="c" />c. 3<br />
<input type="radio" name="q5" value="d" />d. 4<br />
<h3>6. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q6" value="a" />a. 1<br />
<input type="radio" name="q6" value="b" />b. 2<br />
<input type="radio" name="q6" value="c" />c. 3<br />
<input type="radio" name="q6" value="d" />d. 4<br />
<br />
<input type="submit" id="sendA" value="Submit" onclick="score();" />
<br />
<p id="p"></p>
</form>
</body>
</html>
You should wrap value to label value, and use nextSiblingto set color for label.
I updated for high light all correct answer.
answers[index].nextSibling.style.backgroundColor = "red";
var total_seconds = 30 * 1;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);
var timer;
function CheckTime() {
document.getElementById("quiz-time-left").innerHTML =
"Time Left: " + c_minutes + " minutes " + c_seconds + " seconds ";
if (total_seconds <= 0) {
score();
} else {
total_seconds = total_seconds - 1;
c_minutes = parseInt(total_seconds / 60);
c_seconds = parseInt(total_seconds % 60);
timer = setTimeout(CheckTime, 1000);
}
}
timer = setTimeout(CheckTime, 1000);
function highlightAnswerWithClass(question, answer, className) {
var answers = document.forms.form['q'+question];
if(answers == undefined) return;
for (var index = 0; index < answers.length; index++) {
if (answers[index] != null && answers[index].value === answer) {
answers[index].classList.add(className);
if(answers[index].nextSibling.style != undefined) answers[index].nextSibling.style.backgroundColor = "red";
}
}
}
function score() {
// stop timer
clearInterval(timer);
//Referencing the value of the questions
var q1 = document.forms.form.q1.value;
var q2 = document.forms.form.q2.value;
var q3 = document.forms.form.q3.value;
var q4 = document.forms.form.q4.value;
var q5 = document.forms.form.q5.value;
var q6 = document.forms.form.q6.value;
// disable form
var elements = document.getElementById("questions").elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
}
//Array for the questions
var questions = [q1, q2, q3, q4, q5, q6];
//Answers for each question
var answers = ["b", "b", "b", "b", "b", "b"];
//variable to keep track of the points
var points = 0;
var total = 6;
//max score
//Making use of a for loop to iterate over the questions and answers arrays
for (var i = 0; i < total; i++) {
if (questions[i] == answers[i]) {
points = points + 2; //Increment the score by 2 for every correct answer given
//alert(points);
highlightAnswerWithClass(i + 1, questions[i], "correct");
} else {
points = points - 1;
//alert(points);
highlightAnswerWithClass(i + 1, questions[i], "incorrect");
highlightAnswerWithClass(i + 1, answers[i], "correct");
}
}
//CSS for questions
if (points >= 4) {
document.body.style.backgroundColor = "rgba(0,255,0,0.2)";
} else {
document.body.style.backgroundColor = "rgba(255,0,0,0.1)";
}
var q = document.getElementById("p");
q.style.fontSize = "40px";
q.style.textAlign = "center";
q.innerHTML =
"You got " +
points +
" out of " +
total +
"<br />" +
"you used " +
(29 - Math.floor(total_seconds)) +
" seconds";
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
.correct{
border: 1px solid red;
background-color:red;
}
</style>
</head>
<body bgcolor="lightblue">
<div id="quiz-time-left"></div>
<form name="form" id="questions" onsubmit="return false;">
<h3>1. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q1" value="a" />a. 1<br />
<input type="radio" name="q1" value="b" /><label>b. 2</label><br />
<input type="radio" name="q1" value="c" />c. 3<br />
<input type="radio" name="q1" value="d" />d. 4<br />
<h3>2. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q2" value="a" />a. 1<br />
<input type="radio" name="q2" value="b" /><label>b. 2</label><br />
<input type="radio" name="q2" value="c" />c. 3<br />
<input type="radio" name="q2" value="d" />d. 4<br />
<h3>3. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q3" value="a" />a. 1<br />
<input type="radio" name="q3" value="b" /><label>b. 2</label><br />
<input type="radio" name="q3" value="c" />c. 3<br />
<input type="radio" name="q3" value="d" />d. 4<br />
<h3>4. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q4" value="a" />a. 1<br />
<input type="radio" name="q4" value="b" /><label>b. 2</label><br />
<input type="radio" name="q4" value="c" />c. 3<br />
<input type="radio" name="q4" value="d" />d. 4<br />
<h3>5. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q5" value="a" />a. 1<br />
<input type="radio" name="q5" value="b" /><label>b. 2</label><br />
<input type="radio" name="q5" value="c" />c. 3<br />
<input type="radio" name="q5" value="d" />d. 4<br />
<h3>6. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q6" value="a" />a. 1<br />
<input type="radio" name="q6" value="b" /><label>b. 2</label><br />
<input type="radio" name="q6" value="c" />c. 3<br />
<input type="radio" name="q6" value="d" />d. 4<br />
<br />
<input type="submit" id="sendA" value="Submit" onclick="score();" />
<br />
<p id="p"></p>
</form>
</body>
</html>
Ok, so I ran the snippet and here is the error in the console:
Error: {
"message": "Uncaught ReferenceError: Invalid left-hand side expression in prefix operation",
"filename": "https://stacksnippets.net/js",
"lineno": 132,
"colno": 25
}
The error was in line 132 and column 25.
So I think you should check your code before asking stack overflow and you shouldn't just paste your entire code here. Take out the part you think has a problem and then ask us.
Here I took out the code I believe has an error.
Good Luck!
if (points >= 4) {
document.body.style.backgroundColor = "rgba(0,255,0,0.2)";
} else {
document.body.style.backgroundColor = "rgba(255,0,0,0.1)";
}
Your indexing in answers in highlightAnswerWithClass is not correct. answers is an array of all the inputs in the form, it's not grouped by question. Since there are 4 possible answers to each question, the indexes of the answers for a particular question are question*4 through question*4+3.
I'm not sure why you were adding 2 to the question number when calling that function.
I changed your HTML to put a span around the text of each answer. Then I use CSS to change the background of the color.
var total_seconds = 30 * 1;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);
var timer;
function CheckTime() {
document.getElementById("quiz-time-left").innerHTML =
"Time Left: " + c_minutes + " minutes " + c_seconds + " seconds ";
if (total_seconds <= 0) {
score();
} else {
total_seconds = total_seconds - 1;
c_minutes = parseInt(total_seconds / 60);
c_seconds = parseInt(total_seconds % 60);
timer = setTimeout(CheckTime, 1000);
}
}
timer = setTimeout(CheckTime, 1000);
function highlightAnswerWithClass(question, answer, className) {
var answers = document.forms.form;
for (var index = question*4; index < question*4 + 4; index++) {
if (answers[index].value === answer) {
answers[index].classList.add(className);
}
}
}
function score() {
// stop timer
clearInterval(timer);
//Referencing the value of the questions
var q1 = document.forms.form.q1.value;
var q2 = document.forms.form.q2.value;
var q3 = document.forms.form.q3.value;
var q4 = document.forms.form.q4.value;
var q5 = document.forms.form.q5.value;
var q6 = document.forms.form.q6.value;
// disable form
var elements = document.getElementById("questions").elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
}
//Array for the questions
var questions = [q1, q2, q3, q4, q5, q6];
//Answers for each question
var answers = ["b", "b", "b", "b", "b", "b"];
//variable to keep track of the points
var points = 0;
var total = 6;
//max score
//Making use of a for loop to iterate over the questions and answers arrays
for (var i = 0; i < total; i++) {
if (questions[i] == answers[i]) {
points = points + 2; //Increment the score by 2 for every correct answer given
highlightAnswerWithClass(i, questions[i], "correct");
} else {
points = points - 1;
highlightAnswerWithClass(i, questions[i], "incorrect");
highlightAnswerWithClass(i, answers[i], "correct");
}
}
//CSS for questions
if (points >= 4) {
document.body.style.backgroundColor = "rgba(0,255,0,0.2)";
} else {
document.body.style.backgroundColor = "rgba(255,0,0,0.1)";
}
var q = document.getElementById("p");
q.style.fontSize = "40px";
q.style.textAlign = "center";
q.innerHTML =
"You got " +
points +
" out of " +
total +
"<br />" +
"you used " +
(29 - Math.floor(total_seconds)) +
" seconds";
return false;
}
.correct + span {
background-color: green;
}
.incorrect + span {
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body bgcolor="lightblue">
<div id="quiz-time-left"></div>
<form name="form" id="questions" onsubmit="return false;">
<h3>1. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q1" value="a" /><span>a. 1</span><br />
<input type="radio" name="q1" value="b" /><span>b. 2</span><br />
<input type="radio" name="q1" value="c" /><span>c. 3</span><br />
<input type="radio" name="q1" value="d" /><span>d. 4</span><br />
<h3>2. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q2" value="a" /><span>a. 1</span><br />
<input type="radio" name="q2" value="b" /><span>b. 2</span><br />
<input type="radio" name="q2" value="c" /><span>c. 3</span><br />
<input type="radio" name="q2" value="d" /><span>d. 4</span><br />
<h3>3. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q3" value="a" /><span>a. 1</span><br />
<input type="radio" name="q3" value="b" /><span>b. 2</span><br />
<input type="radio" name="q3" value="c" /><span>c. 3</span><br />
<input type="radio" name="q3" value="d" /><span>d. 4</span><br />
<h3>4. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q4" value="a" /><span>a. 1</span><br />
<input type="radio" name="q4" value="b" /><span>b. 2</span><br />
<input type="radio" name="q4" value="c" /><span>c. 3</span><br />
<input type="radio" name="q4" value="d" /><span>d. 4</span><br />
<h3>5. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q5" value="a" /><span>a. 1</span><br />
<input type="radio" name="q5" value="b" /><span>b. 2</span><br />
<input type="radio" name="q5" value="c" /><span>c. 3</span><br />
<input type="radio" name="q5" value="d" /><span>d. 4</span><br />
<h3>6. How many yellow cards equal a red card in football?</h3>
<input type="radio" name="q6" value="a" /><span>a. 1</span><br />
<input type="radio" name="q6" value="b" /><span>b. 2</span><br />
<input type="radio" name="q6" value="c" /><span>c. 3</span><br />
<input type="radio" name="q6" value="d" /><span>d. 4</span><br />
<span> </span><br />
<input type="submit" id="sendA" value="Submit" onclick="score();" />
<br />
<p id="p"></p>
</form>
</body>
</html>

change label text of all radio button in quiz as red and green

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>

how to use loops in a javascript quiz

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');
}
}});
}
}

How to convert Javascript quiz to show a button after a a combination of buttons are chosen

I'm trying to figure out how to change this code around so that when someone answers certain questions, they will get certain a certain link or button depending on the combination of questions asked. I prefer to use javascript and HTML because that's all I know.
<html>
<head>
<style type="text/css">
<!--
.bgclr {background-color: white; color: black; font-weight: bold;}
-->
</style>
<script language="JavaScript">
This script and many more are available free online at
The JavaScript Source!! http://www.javascriptsource.com
<!-- Begin
// Insert number of questions
var numQues = 4;
// Insert number of choices in each question
var numChoi = 3;
// Insert number of questions displayed in answer area
var answers = new Array(4);
// Insert answers to questions
answers[0] = "Cascading Style Sheets";
answers[1] = "Dynamic HTML";
answers[2] = "Netscape";
answers[3] = "Common Gateway Interface";
// 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++;
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;
}
// End -->
</script>
</head>
<body>
<h3>Web Design Quiz</h3>
<form name="quiz">
1. What does CSS stand for?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q1" value="Colorful Style Symbols"/>Colorful Style
Symbols</li>
<li><input type="radio" name="q1" value="Cascading Style Sheets"/>Cascading Style
Sheets</li>
<li><input type="radio" name="q1" value="Computer Style Symbols"/>Computer Style
Symbols</li>
</ul>
2. What does DHTML stand for?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q2" value="Dramatic HTML"/>Dramatic HTML</li>
<li><input type="radio" name="q2" value="Design HTML"/>Design HTML</li>
<li><input type="radio" name="q2" value="Dynamic HTML"/>Dynamic HTML</li>
</ul>
3. Who created Javascript?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q3" value="Microsoft"/>Microsoft</li>
<li><input type="radio" name="q3" value="Netscape"/>Netscape</li>
<li><input type="radio" name="q3" value="Sun Micro Systems"/>Sun Micro Systems</li>
</ul>
4. What does CGI stand for?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q4" value="Cascading Gate Interaction"/>Cascading Gate
Interaction</li>
<li><input type="radio" name="q4" value="Common GIF Interface"/>Common GIF
Interface</li>
<li><input type="radio" name="q4" value="Common Gateway Interface"/>Common Gateway
Interface</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="disabled"/></strong><br/><br/>
Correct answers:<br/>
<textarea class="bgclr" name="solutions" wrap="virtual" rows="4" cols="30"
disabled="disabled">
</textarea>
</p></form>
</body>
</html>`
JSFiddle: http://jsfiddle.net/ThqmR/

Printing JavaScript Quiz Results on a new page on clicking submit

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.

Categories

Resources