Two independent scripts getting mixed up and giving unexpected output - javascript

I am trying to serve 2 quizzes on the same page, however when I click the button Get Score, the first one doesn't work. I have got these two Javascripts in the head:
<script language="JavaScript">
var q1numQues = 5;
var q1numChoi = 4;
var q1answers = new Array(5);
q1answers[0] = "11";
q1answers[1] = "3";
q1answers[2] = "8";
q1answers[3] = "15";
q1answers[4] = "4";
function getQuiz1Score(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < q1numQues; i++) {
currElt = i * q1numChoi;
for (j = 0; j < q1numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == q1answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score / q1numQues * 100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i = 1; i <= q1numQues; i++) {
correctAnswers += i + ". " + q1answers[i - 1] + "\r\n";
}
form.solutions.value = correctAnswers;
break;
}
</script>
<script language="JavaScript">
var q2numQues = 4;
var q2numChoi = 3;
var q2answers = new Array(4);
q2answers[0] = "UK";
q2answers[1] = "USA";
q2answers[2] = "Mexico";
q2answers[3] = "Canada";
function getQuiz2Score(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < q2numQues; i++) {
currElt = i * q2numChoi;
for (j = 0; j < q2numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == q2answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score / q2numQues * 100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i = 1; i <= q2numQues; i++) {
correctAnswers += i + ". " + q2answers[i - 1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
</script>
And these are my quizzes:
<div class="container" id="pill">
<ul class="nav nav-pills">
<li class="active"><a data-toggle="tab" href="#mathquiz">Maths Quiz</a></li>
<li><a data-toggle="tab" href="#geographyquiz">Geography Quiz</a></li>
</ul>
<div class="tab-content">
<div id="mathquiz" class="tab-pane fade in active">
<div class="image-container">
<img src="images/math.png" class="img-responsive" alt="Our Values Banner">
</div>
<br>
<h4 align="center">Maths Quiz - Please click Get Score after completing to get your score</h4>
<form name="quiz" align="center"> <b>
1. What is 4+7?<br>
<input type="radio" name="q1" value="5">5<br>
<input type="radio" name="q1" value="10">10<br>
<input type="radio" name="q1" value="11">11<br>
<input type="radio" name="q1" value="20">20<br>
2. What is 5-2?<br>
<input type="radio" name="q2" value="0">0<br>
<input type="radio" name="q2" value="5">5<br>
<input type="radio" name="q2" value="3">3<br>
<input type="radio" name="q2" value="8">8<br>
3. What is 4*2?<br>
<input type="radio" name="q3" value="33">33<br>
<input type="radio" name="q3" value="20">20<br>
<input type="radio" name="q3" value="1">1<br>
<input type="radio" name="q3" value="8">8<br>
4. What is 3+12?<br>
<input type="radio" name="q4" value="15">15<br>
<input type="radio" name="q4" value="4">4<br>
<input type="radio" name="q4" value="78">78<br>
<input type="radio" name="q4" value="1">1<br>
5. What is 8/2?<br>
<input type="radio" name="q5" value="4">4<br>
<input type="radio" name="q5" value="7">7<br>
<input type="radio" name="q5" value="9">9<br>
<input type="radio" name="q5" value="8">8<br>
<input type="button" value="Get score" onClick="getQuiz1Score(this.form)">
<input type="reset" value="Clear">
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea> </b>
</form>
</div>
<div id="geographyquiz" class="tab-pane fade">
<div class="image-container">
<img src="images/geography.jpg" class="img-responsive" alt="Geography Quiz">
</div>
<h4 align="center">Geography Quiz</h4>
<form name="quiz" align="center"> <b>
Identify the country the flag belongs to! <br><br>
1. <div class="image-container">
<img src="images/britishflag.png" class="img-responsive" alt="British Flag">
</div><br>
<input type="radio" name="q1" value="UK">UK<br>
<input type="radio" name="q1" value="Germany">Germany<br>
<input type="radio" name="q1" value="Italy">Italy<br><br>
2. <div class="image-container">
<img src="images/usaflag.png" class="img-responsive" alt="USA Flag">
</div><br>
<input type="radio" name="q2" value="Ireland">Ireland<br>
<input type="radio" name="q2" value="Belgium">Belgium<br>
<input type="radio" name="q2" value="USA">USA<br><br>
3. <div class="image-container">
<img src="images/mexicoflag.png" class="img-responsive" alt="Mexican Flag">
</div><br>
<input type="radio" name="q3" value="Brazil">Brazil<br>
<input type="radio" name="q3" value="Mexico">Mexico<br>
<input type="radio" name="q3" value="Chile">Chile<br><br>
4. <div class="image-container">
<img src="images/canadaflag.png" class="img-responsive" alt="Canadian Flag">
</div><br>
<input type="radio" name="q4" value="Japan">Japan<br>
<input type="radio" name="q4" value="Portugal">Portugal<br>
<input type="radio" name="q4" value="Canada">Canada<br>
<input type="button" value="Get score" onClick="getQuiz2Score(this.form)">
<input type="reset" value="Clear">
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea> </b>
</form>
</div>
Please help me to make the Get Score buttons work.

Note: The following was relevant before the OP made edits to implement the changes suggested below. The fix for the OP came down to a superfluous break as pointed out in Rion Williams's answer.
The first script starts with
<script language="JavaScript">
<!--
var numQues = 5;
var numChoi = 4;
What is that <!-- doing there? You delimit this comment later in the script but you comment out the delimeter by writing // -->.
Anyways, your second script starts with
<script language="JavaScript">
var numQues = 4;
var numChoi = 3;
Something you need to understand is that you're declaring these variables globally; at any given point in time, numQuest in script A is the exact same as numQuest in script B (and vice versa) . Due to the nature of declaring variables globally in JavaScript, when you write
var numQuest = 5;
you're effectively writing
window.numQuest = 5;
which sets the variable numQuest as defined and accessible across the entire Browser Object Model (BOM). Read this resource on window and BOM.
You need to either rename your variables or scope the variables like so:
<script language="JavaScript">
(function() {
var numQues = 5;
var numChoi = 4;
... rest of code ...
})();
</script>
I would suggest that you thoroughly read this:
https://stackoverflow.com/a/8348725/5137782

Scoping and Function Overwriting Issues
Currently the names of your functions are the same getScore(name) so the second declaration is actually overwriting the first and your variables are doing the same.
Consider changing each of them to getQ1Score() and getQ2Score() respectively along with where they are called and appending q1 and q2 to your variables and their declarations as well :
// Quiz 1 variables
var q1numQues = 5;
var q1numChoi = 4;
var q1answers = ["11", "3", "8", "15", "4"];
// Quiz 1 score function
function getQ1Score(form) {
/* Omitted for brevity (but ensure you update your variable names too) */
}
along with :
<!-- This will explicitly call your Q1 score calculation -->
<input type="button" value="Get score" onclick="getQ1Score(this.form)">
These are the break;s
Additionally, you have a straggling break; statement at then of your getQuiz1Score(), which would cause things to freak out :
// Remove this to get things up and running
break;
Consider Refactoring A Bit
Overall, you may want to consider some of the points addressed in 8proton's response regarding scoping your functions so you wouldn't have to worry about renaming everything (especially if you intend to add some additional quizzes in the future).
Example Output and Snippet With Updated Changes
// Quiz 1 variables
var q1numQues = 5;
var q1numChoi = 4;
var q1answers = ["11", "3", "8", "15", "4"];
// Quiz 1 score function
function getQ1Score(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < q1numQues; i++) {
currElt = i * q1numChoi;
for (j = 0; j < q1numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score / q1numQues * 100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i = 1; i <= q1numQues; i++) {
correctAnswers += i + ". " + q1answers[i - 1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
// -->
// Quiz 2 variables
var q2numQues = 4;
var q2numChoi = 3;
var q2answers = ["UK", "USA", "Mexico", "Canada"];
// Quiz 2 score function
function getQ2Score(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < q2numQues; i++) {
currElt = i * q2numChoi;
for (j = 0; j < q2numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == q2answers[i]) {
score++;
break;
}
}
}
}
score = Math.round(score / q2numQues * 100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i = 1; i <= q2numQues; i++) {
correctAnswers += i + ". " + q2answers[i - 1] + "\r\n";
}
form.solutions.value = correctAnswers;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="tab-content">
<div id="mathquiz" class="tab-pane fade in active">
<div class="image-container">
<img src="images/math.png" class="img-responsive" alt="Our Values Banner">
</div>
<br>
<h4 align="center">Maths Quiz - Please click Get Score after completing to get your score</h4>
<form name="quiz1" align="center"> <b>
1. What is 4+7?<br>
<input type="radio" name="q1" value="5">5<br>
<input type="radio" name="q1" value="10">10<br>
<input type="radio" name="q1" value="11">11<br>
<input type="radio" name="q1" value="20">20<br>
2. What is 5-2?<br>
<input type="radio" name="q2" value="0">0<br>
<input type="radio" name="q2" value="5">5<br>
<input type="radio" name="q2" value="3">3<br>
<input type="radio" name="q2" value="8">8<br>
3. What is 4*2?<br>
<input type="radio" name="q3" value="33">33<br>
<input type="radio" name="q3" value="20">20<br>
<input type="radio" name="q3" value="1">1<br>
<input type="radio" name="q3" value="8">8<br>
4. What is 3+12?<br>
<input type="radio" name="q4" value="15">15<br>
<input type="radio" name="q4" value="4">4<br>
<input type="radio" name="q4" value="78">78<br>
<input type="radio" name="q4" value="1">1<br>
5. What is 8/2?<br>
<input type="radio" name="q5" value="4">4<br>
<input type="radio" name="q5" value="7">7<br>
<input type="radio" name="q5" value="9">9<br>
<input type="radio" name="q5" value="8">8<br>
<input type="button" value="Get score" onclick="getQ1Score(this.form)">
<input type="reset" value="Clear">
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea> </b>
</form>
</div>
<div id="geographyquiz" class="tab-pane fade">
<div class="image-container">
<img src="images/geography.jpg" class="img-responsive" alt="Geography Quiz">
</div>
<h4 align="center">Geography Quiz</h4>
<form name="quiz2" align="center"> <b>
Identify the country the flag belongs to! <br><br>
1. <div class="image-container">
<img src="images/britishflag.png" class="img-responsive" alt="British Flag">
</div><br>
<input type="radio" name="q1" value="UK">UK<br>
<input type="radio" name="q1" value="Germany">Germany<br>
<input type="radio" name="q1" value="Italy">Italy<br><br>
2. <div class="image-container">
<img src="images/usaflag.png" class="img-responsive" alt="USA Flag">
</div><br>
<input type="radio" name="q2" value="Ireland">Ireland<br>
<input type="radio" name="q2" value="Belgium">Belgium<br>
<input type="radio" name="q2" value="USA">USA<br><br>
3. <div class="image-container">
<img src="images/mexicoflag.png" class="img-responsive" alt="Mexican Flag">
</div><br>
<input type="radio" name="q3" value="Brazil">Brazil<br>
<input type="radio" name="q3" value="Mexico">Mexico<br>
<input type="radio" name="q3" value="Chile">Chile<br><br>
4. <div class="image-container">
<img src="images/canadaflag.png" class="img-responsive" alt="Canadian Flag">
</div><br>
<input type="radio" name="q4" value="Japan">Japan<br>
<input type="radio" name="q4" value="Portugal">Portugal<br>
<input type="radio" name="q4" value="Canada">Canada<br>
<input type="button" value="Get score" onClick="getQ2Score(this.form)">
<input type="reset" value="Clear">
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea> </b>
</form>
</body>
</html>

Related

How do I know if a user has selected an option in a form in html + javascript

I am trying to build a quiz with questions and options but I don't know how to add the options to the quiz. Also, I want to know if I selected the correct option and if the number of correct answers is shown at the end. Can someone help me build this?
I have tried adding options but I can't get the output needed.
<form align="center" id = "test">
Question 1: <input type="radio" name="radiogroup1" value="radio" id="radiogroup1"> Option 1
<input type="radio" name="radiogroup1" value="radio" id="radiogroup2"> Option 2 <br><be>
</form>
See if this helps you: (just an example to get the idea)
function submitAnswers() {
var total = 5;
var score = 0;
//Get user input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
var q4 = document.forms["quizForm"]["q4"].value;
var q5 = document.forms["quizForm"]["q5"].value;
// Validation
for (var i = 1; i <= total; i++) {
if (eval('q' + i) == null || eval('q' + i) == '') {
alert("you missed question " + i);
return false;
}
}
//set correct answers
var answers = ["b", "d", "c", "a", "b"]
//check answers
for (var i = 1; i <= total; i++) {
if (eval('q' + i) == answers[i - 1]) {
score++;
}
}
alert('You scored ' + score + " out of " + total);
return false;
}
<div class="container">
<section>
<form name="quizForm" onsubmit="submitAnswers(); return false">
<h3>1. Question number one?</h3>
<input type="radio" name="q1" value="a" id="q1a"> a. answer11<br>
<input type="radio" name="q1" value="b" id="q1b"> b. answer12<br>
<input type="radio" name="q1" value="c" id="q1c"> c. answer13<br>
<input type="radio" name="q1" value="d" id="q1d"> d. answer14<br>
<h3>2. Question number two?</h3>
<input type="radio" name="q2" value="a" id="q2a"> a. answer21<br>
<input type="radio" name="q2" value="b" id="q2b"> b. answer22<br>
<input type="radio" name="q2" value="c" id="q2c"> c. answer23<br>
<input type="radio" name="q2" value="d" id="q2d"> d. answer24<br>
<h3>3. Question number three?</h3>
<input type="radio" name="q3" value="a" id="q3a"> a. answer31<br>
<input type="radio" name="q3" value="b" id="q3b"> b. answer32<br>
<input type="radio" name="q3" value="c" id="q3c"> c. answer33<br>
<input type="radio" name="q3" value="d" id="q3d"> d. answer34<br>
<h3>4. Question number four ?</h3>
<input type="radio" name="q4" value="a" id="q4a"> a. answer41<br>
<input type="radio" name="q4" value="b" id="q4b"> b. answer42<br>
<input type="radio" name="q4" value="c" id="q4c"> c. answer43<br>
<input type="radio" name="q4" value="d" id="q4d"> d. answer44<br>
<h3>5. Question number five ?</h3>
<input type="radio" name="q5" value="a" id="q5a">a. answer51<br>
<input type="radio" name="q5" value="b" id="q5b">b. answer52<br>
<br><br>
<input type="submit" value="Submit Answers">
</form>
</section>
</div>

Sum of Radio button values printed to the user

I'm very new to html.
I have a survey with two questions where the question choices are presented with radio buttons as this html code shows:
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
</form>
I want to print to the user the sum of his two selections.
So the output could be "You score is 10." if he answered yes to both questions etc.
How can I do this in the simplest way with the code being on the same page as the html code above? Is that possible?
var question1Answers = document.getElementsByName('q1');
var question2Answers = document.getElementsByName('q2');
var answer = 0;
question1Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
question2Answers.forEach((e) => {
if (e.checked) {
answer += e.value;
break;
}
});
console.log(answer);
please try this:
$("input[type='button']").click(function () {
var score = getChecklistItems();
alert("You score is : " + score);
});
function getChecklistItems() {
var total_score = 0
var result = $("input:radio:checked").get();
var checked_value = $.map(result, function (element) {
return $(element).attr("value");
});
for (i = 0; i < checked_value.length; i++) {
total_score += parseInt(checked_value[i])
}
return total_score
}
<form>
<p id="description">1. Question 1?</p>
<p>
<label><input type="radio" name="q1" value="5" /> Yes</label>
<label><input type="radio" name="q1" value="0" /> No</label>
</p>
<p id="description">2. Question 2?</p>
<p>
<label><input type="radio" name="q2" value="5" /> Yes</label>
<label><input type="radio" name="q2" value="0" /> No</label>
</p>
<p><input type="button" value="Submit"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

My countdown timer is not working

I am attaching my .js as well as php file, no output is being displayed on the screen not even the __________ placed in the <p> tag ,the php file is only up to the <p> tag where the id for the .js file is attached.
js code:
var timeleft = 600;
var startTime = 0;
var currentTime = 0;
function convertSeconds(s) {
var min = floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ':' + nf(sec, 2);
}
var ding;
function preload() {
ding = loadSound("ding.mp3");
}
function setup() {
noCanvas();
startTime = millis();
var params = getURLParams();
console.log(params);
if (params.minute) {
var min = params.minute;
timeleft = min * 60;
}
var timer = select('#timer');
timer.html(convertSeconds(timeleft - currentTime));
var interval = setInterval(timeIt, 1000);
function timeIt() {
currentTime = floor((millis() - startTime) / 1000);
timer.html(convertSeconds(timeleft - currentTime));
if (currentTime == timeleft) {
ding.play();
clearInterval(interval);
//counter = 0;
}
}
}
html code:
<html>
<head>
<title>online examination system</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="style2.css">
<meta charset="UTF-8">
<script language="javascript" type="text/javascript src=" libraries
/p5.js</script>
< script language = "javascript"
src = "libraries/p5.dom.js" ></script>
<script language="javascript" src="libraries/p5.sound.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
</head>
<body>
<div class=header>
<img class="img-style" src="Online-Examination-System-Banner.jpeg" width="1166px" height="250px">
</div>
<div class="top">
<ul id="navigation">
<li>HOME</li>
<li>ABOUT US</li>
<li>CONTACT US</li>
<li>EXAMINATION</li>
<li>LOGIN</li>
<li>LOGOUT</li>
</ul>
</div>
<p style="font-size:40;color:white;font-weight:bolder;">Welcome !</p>
<p id="timer" style="color:white;font-family:courier;font-size:28px; float:center;">______</p>
<form action="cplus.php" method="post" >
<div style="margin-top:10px;margin-right:85px;margin-left:100px;margin- bottom:20px;background:rgba(0,0,0,0.5)">
<p style="color:white;font-family:courier;font-size:18px">1. Which of the following correctly declares an array?</p> <br>
<input class="exam-btn" type="radio" name="q1" id="q1-a" value="A" checked>
<label for="q1-a" style="color:white;font-family:courier;font-size:18px">int array[10];</label>
<input class="exam-btn" type="radio" name="q1" id="q1-b" value="B">
<label style="color:white;font-family:courier;font-size:18px">int array;</label>
<input class="exam-btn" type="radio" name="q1" id="q1-c" value="C">
<label style="color:white;font-family:courier;font-size:18px">array{10};</label>
<input class="exam-btn" type="radio" name="q1" id="q1-d" value="D">
<label style="color:white;font-family:courier;font-size:18px">array array[10];</label>
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">2. What is the index number of the last element of an array with 9 elements?</p> <br>
<input class="exam-btn" type="radio" name="q2" id="q2-a" value="A">
<label style="color:white;font-family:courier;font-size:18px">9</label>
<input class="exam-btn" type="radio" name="q2" id="q2-b" value="B" checked>
<label style="color:white;font-family:courier;font-size:18px">8</label>
<input class="exam-btn" type="radio" name="q2" id="q2-c" value="C">
<label style="color:white;font-family:courier;font-size:18px">0</label>
<input class="exam-btn" type="radio" name="q2" id="q2-d" value="D">
<label style="color:white;font-family:courier;font-size:18px">programmer defined</label>
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">3. Which of the following accesses the seventh element stored in array?</p> <br>
<input class="exam-btn" type="radio" name="q3" id="q3-a" value="A" checked>
<label style="color:white;font-family:courier;font-size:18px">array[6];</label>
<input class="exam-btn" type="radio" name="q3" id="q3-b" value="B" >
<label style="color:white;font-family:courier;font-size:18px">array[7];</label>
<input class="exam-btn" type="radio" name="q3" id="q3-c" value="C" >
<label style="color:white;font-family:courier;font-size:18px">array(7);</label>
<input class="exam-btn" type="radio" name="q3" id="q3-d" value="D" >
<label style="color:white;font-family:courier;font-size:18px">array;</label>
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">4. Which of the following gives the memory address of the first element in array?</p> <br>
<input class="exam-btn" type="radio" name="q4" id="q4-a" value="A" >
<label style="color:white;font-family:courier;font-size:18px">array[0];</label>
<input class="exam-btn" type="radio" name="q4" id="q4-b" value="B" >
<label style="color:white;font-family:courier;font-size:18px">array[1];</label>
<input class="exam-btn" type="radio" name="q4" id="q4-c" value="C" >
<label style="color:white;font-family:courier;font-size:18px">array[2];</label>
<input class="exam-btn" type="radio" name="q4" id="q4-d" value="D" checked>
<label style="color:white;font-family:courier;font-size:18px">none</label>
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">5. What will be the output of this program?</p> <br>
<pre style="color:white;font-family:courier;font-size:18px">
#include <stdio.h>
using namespace std;
int array1[] = {1200, 200, 2300, 1230, 1543};
int array2[] = {12, 14, 16, 18, 20};
int temp, result = 0;
int main()
{
for (temp = 0; temp < 5; temp++)
{
result += array1[temp];
}
for (temp = 0; temp < 4; temp++)
{
result += array2[temp];
}
cout << result;
return 0;
}
</pre>
</pre>
<input class="exam-btn" type="radio" name="q5" id="q5-a" value="A" >
<label style="color:white;font-family:courier;font-size:18px">6553</label>
<input class="exam-btn" type="radio" name="q5" id="q5-b" value="B" checked>
<label style="color:white;font-family:courier;font-size:18px">6533</label>
<input class="exam-btn" type="radio" name="q5" id="q5-c" value="C" >
<label style="color:white;font-family:courier;font-size:18px">6522</label>
<input class="exam-btn" type="radio" name="q5" id="q5-d" value="D" >
<label style="color:white;font-family:courier;font-size:18px">12200</label>
<br><br><br><br>
<! 1. token 2. sensitive 3. identifiers
4. octal 5. \0n -->
<p style="color:white;font-family:courier;font-size:18px">6.The smallest individual unit in a program is known as a …………………… </p> <br>
<p style="color:white;font-family:courier;font-size:18px">ans</p><input class="exam-btn" type="text" name="" >
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">7.C++ Language is case …………………. </p> <br>
<p style="color:white;font-family:courier;font-size:18px">ans</p><input class="exam-btn" type="text" name="" >
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">8.An ………………… is a long sequence of letters and digits. </p> <br>
<p style="color:white;font-family:courier;font-size:18px">ans</p><input class="exam-btn" type="text" name="" >
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">9.A sequence of digits beginning with zero is considered to be …………….number. </p> <br>
<p style="color:white;font-family:courier;font-size:18px">ans</p><input class="exam-btn" type="text" name="" >
<br><br><br><br>
<p style="color:white;font-family:courier;font-size:18px">10.………………. escape sequence represents the given number in octal form. </p> <br>
<p style="color:white;font-family:courier;font-size:18px">ans</p>
<input class="exam-btn" type="text" name="" >
<br><br><br><br>
<input type="submit" value="Submit quiz">
</div>
<div style="font-size:18px;color:white;font-weight:bolder;">
<?php
$answer1;
$answer2;
$answer3;
$answer4;
$answer5;
$answer1 = $_POST['q1'];
$answer2 = $_POST['q2'];
$answer3 = $_POST['q3'];
$answer4 = $_POST['q4'];
$answer5 = $_POST['q5'];
$totalcorrect;
$totalcorrect = 0;
if($answer1 == "A") {$totalcorrect++;}
if($answer2 == "B") {$totalcorrect++;}
if($answer3 == "A") {$totalcorrect++;}
if($answer4 == "D") {$totalcorrect++;}
if($answer5 == "B") {$totalcorrect++;}
echo "total correct answers are".$totalcorrect;
?>
</div>
</div>
</form>
</body>
</html>

multiple choice quiz with class correct and wrong

I created a multiple choice quiz, and it working perfectly, I mean get the total score written on the website, but I wish to change it to just giving an extra 'correct' or 'wrong' CSS class to the selected input radio buttons after the Submit button has been hit.
HTML:
<section class="quiz">
<div id="results"></div>
<form name="quizForm" onsubmit="return submitAnswer()">
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 1</h4>
<p>Question 1</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q1" value="a" id="q1a"><label for="q1a">Test 1</label><br>
<input data-answer type="radio" name="q1" value="b" id="q1b"><label for="q1b">Test 2</label><br>
<input data-answer type="radio" name="q1" value="c" id="q1c"><label for="q1c">Test 3</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 2</h4>
<p>Question 2</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q2" value="a" id="q2a"><label for="q2a">Test 4</label><br>
<input data-answer type="radio" name="q2" value="b" id="q2b"><label for="q2b">Test 5</label><br>
<input data-answer type="radio" name="q2" value="c" id="q2c"><label for="q2c">Test 6</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 3</h4>
<p>Question 3</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q3" value="a" id="q3a"><label for="q3a">Test 7</label><br>
<input data-answer type="radio" name="q3" value="b" id="q3b"><label for="q3b">Test 8</label><br>
<input data-answer type="radio" name="q3" value="c" id="q3c"><label for="q3c">Test 9</label><br>
</div>
<h4 class="quiz-title knowledge-content-list-item-subheader">Question 4</h4>
<p>Question 4</p>
<div class="quiz-answers">
<input data-answer type="radio" name="q4" value="a" id="q4a"><label for="q4a">Test 10</label><br>
<input data-answer type="radio" name="q4" value="b" id="q4b"><label for="q4b">Test 11</label><br>
<input data-answer type="radio" name="q4" value="c" id="q4c"><label for="q4c">Test 12</label><br>
</div>
<button id="btn-submit" class="btn btn-submit" type="submit" name="submit" value="submit">submit</button>
</form>
</div>
</section>
JavaScript:
function submitAnswer() {
var total = 4;
var score = 0;
// Get User Input
var q1 = document.forms["quizForm"]["q1"].value;
var q2 = document.forms["quizForm"]["q2"].value;
var q3 = document.forms["quizForm"]["q3"].value;
var q4 = document.forms["quizForm"]["q4"].value;
// Validation
for(i = 1; i <= total; i++){
if(eval('q'+i) == null || eval('q'+i) == ''){
alert('You missed question '+ i);
return false;
}
}
// Set Correct Answers
var answers = ["a", "b", "c", "a"];
// Check Answers
for(i = 1; i <= total; i++){
if(eval('q'+i) == answers[i - 1]){
score++;
}
}
// Display results
var results = document.getElementById('results');
results.innerHTML = '<h3>You scored <span>'+score+'</span> out of <span>'+total+'</span></h3>';
return false;
}
I would be really appreciated for any kind of help. Cheers
You can use classLis.add() for that. So in your JS you'd do
document.getElementById('q4a').classList.add('correct')
document.getElementById('q4b').classList.add('wrong')
document.getElementById('q4c').classList.add('wrong')

JavaScript quiz answer check up

I'm trying to make a score base quiz where it shows how much score you get when finished e.g. out of 8 and the answers you got incorrect. I have the score system out of the way, just not the validation
HTML
<div class="quiz">
1) What noise does a dog make?</div>
<div class="values">
<input type="radio" value="0" id="q1" name="q1" onclick="question('jq1',this.value)">a) Cluck<br>
<input type="radio" value="0" id="q1" name="q1" onclick="question('jq1',this.value)">b) Meow<br>
<input type="radio" value="0" id="q1" name="q1" onclick="question('jq1',this.value)">c) Moo<br>
<input type="radio" value="1" id="q1" name="q1" onclick="question('jq1',this.value)">d) Woof</div><br>
<input type="hidden" name="jq1" id="jq1" />
<div class="quiz">
2) What noise does a cat make?</div>
<div class="values">
<input type="radio" value="1" id="q2" name="q2" onclick="question('jq2',this.value)">a) Meow<br>
<input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">b) Cluck<br>
<input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">c) Woof<br>
<input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">d) Moo</div><br>
<input type="hidden" name="jq2" id="jq2" />
(sorry for inappropriate questions, they're just there as placeholders :D)
JavaScript
function question(ref,val) {
var x = document.getElementById(ref);
x.value = val;
}
function result() {
var score = 0;
var x = document.getElementById('jq1');
score = eval (score) + eval(x.value);
var x = document.getElementById('jq2');
score = eval (score) + eval(x.value);
alert("You scored: "+score +" out of 2!");
}
I'd like a new line underneath the current one in the alert box saying "Questions 1, 2, 3 were incorrect". Just very unsure on how to do this and would like someone's help.
Thanks very much!
A more object oriented answer
DEMO: http://jsfiddle.net/Victornpb/3cwzndp8/1/
var q = [
{
question:"What noise does a dog make?",
options:["Meow", "Cluck","Woof","Moo"],
answers: [0,0,1,0]
},
{
question:"What noise does a cat make?",
options:["Meow", "Cluck","Woof","Moo"],
answers: [1,0,0,0]
}
];
var questionary = generateQuestionary(q);
quizBody.appendChild(questionary);
function generateQuestionary(obj){
var questionary = tag("div",{className:"questionary"});
for(var i=0; i<obj.length; i++){
questionary.appendChild(generateQuestionHtml(obj[i], i));
}
return questionary;
}
function generateQuestionHtml(obj, n){
var answers = tag("div",{className:"answers"});
for(var i=0; i<obj.options.length; i++){
answers.appendChild(
tag("label",{},
tag("input",{type:"radio", name:"q"+n, value:obj.answers[i],onclick:ck} ),
tag("span",{}, obj.options[i]),
tag("br")
)
);
}
return tag("div",{className:"quiz"},
tag("div",{className:"question"}, obj.question),
answers,
tag("div",{className:"info"})
);
}
function ck(e){
console.log(this);
var infoBox = this.parentElement.parentElement.parentElement.getElementsByClassName("info")[0];
if(this.value==1){
infoBox.innerHTML = "Correct!";
infoBox.classList.remove("wrong");
}
else{
infoBox.innerHTML = "Incorrect answer :(";
infoBox.classList.add("wrong");
}
}
I used a utility function to generate the DOM Elements (the tag() function)
https://gist.github.com/victornpb/11201998
Assuming you want a rudimentary, client-side system, I would suggest declaring an object that holds the answers when the page loads, with the name of each group of choices as the key, and the correct answers being the values.
Say that question 1, labeled "q1", has 3 choices, the answer being the first.
var answers = {q1:0, q2:3};
//The key "q1" gets the value 0, while "q2" will get 3 (or any arbitrary value you want)
Now you can say
if(answers["q1"] != document.forms["formNameHere"].elements["q1"].value)
alert("Everything is awful, you got question one wrong");
You can iterate through each question, checking if the answer is correct, and assembling a string of the wrong answers, which you can display through your alert on a new line.
It's not clear what you want to accomplish.
eval is totally unnecessary here, and shouldn't be used.
window.onload = function() {
check.onclick = result;
}
function result() {
var score = 0;
score += parseInt(getSelectedRadioValue("q1")) || 0;
score += parseInt(getSelectedRadioValue("q2")) || 0;
alert("You scored: " + score + " out of 2!");
}
function getSelectedRadioValue(name) {
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
}
<div class="quiz">
1) What noise does a dog make?</div>
<div class="answers">
<label>
<input type="radio" value="0" name="q1">a) Meow</label>
<br>
<label>
<input type="radio" value="0" name="q1">b) Cluck</label>
<br>
<label>
<input type="radio" value="1" name="q1">c) Woof</label>
<br>
<label>
<input type="radio" value="0" name="q1">d) Moo</label>
<br>
</div>
<br>
<input type="hidden" name="jq1" id="jq1" />
<div class="quiz">
2) What noise does a cat make?</div>
<div class="answers">
<label>
<input type="radio" value="1" name="q2">a) Meow</label>
<br>
<label>
<input type="radio" value="0" name="q2">b) Cluck</label>
<br>
<label>
<input type="radio" value="0" name="q2">c) Woof</label>
<br>
<label>
<input type="radio" value="0" name="q2">d) Moo</label>
<br>
</div>
<br>
<input type="hidden" name="jq2" id="jq2" />
<input type="button" id="check" value="I'm done">
Demo:
https://quiz-using-javascript.web.app/
Source Code:
https://github.com/mhsunny/JavaScript-Quiz
This is the project to build a quiz using JavaScript. You can find how to check the answer of questions using javascript forEach() and using setInterval and clearInteval method.
app.js
app.js
const correctAnswers = ['B', 'B', 'B', 'B'];
const form = document.querySelector('.quiz-form');
const result = document.querySelector('.result');
form.addEventListener('submit', e =>{
e.preventDefault();
let score = 0;
const userAnswer = [form.q1.value, form.q2.value, form.q3.value, form.q4.value]
//check answers
userAnswer.forEach((answer, index) =>{
if(answer === correctAnswers[index]){
score +=25;
}
// console.log(score);
//show result on page
});
scrollTo(0, 0);
result.classList.remove('d-none');
let output = 0;
const timer = setInterval(()=>{
result.querySelector('span').textContent = `${output}%`;
if(output === score){
clearInterval(timer);
}else{
output++;
}
}, 10)
})
// let i = 0;
// const timer = setInterval(()=>{
// console.log("hello")
// i++;
// if(i == 5){
// clearInterval(timer);
// }
// }, 1000)
index.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> JavaScript Quiz</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<!-- top section -->
<div class="intro py-3 bg-white text-center">
<div class="container">
<h2 class="text-primary display-3 my-4"> Quiz using Javascript</h2>
</div>
</div>
<!-- result section -->
<div class="result py-4 d-none bg-light text-center">
<div class="container lead">
<p>You are <span class="text-primary display-4 p-3">0%</span> ninja</p>
</div>
</div>
<!-- quiz section -->
<div class="quiz py-4 bg-primary">
<div class="container">
<h2 class="my-5 text-white">On with the questions...</h2>
<form class="quiz-form text-light">
<div class="my-5">
<p class="lead font-weight-normal">1. How do you give a ninja directions?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q1" value="A" checked>
<label class="form-check-label">Show them a map</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q1" value="B">
<label class="form-check-label">Don't worry, the ninja will find you</label>
</div>
</div>
<div class="my-5">
<p class="lead font-weight-normal">2. If a ninja has 3 apples, then gives one to Mario & one to Yoshi, how many apples does the ninja have left?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q2" value="A" checked>
<label class="form-check-label">1 apple</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q2" value="B">
<label class="form-check-label">3 apples, and two corpses</label>
</div>
</div>
<div class="my-5">
<p class="lead font-weight-normal">3. How do you know when you've met a ninja?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q3" value="A" checked>
<label class="form-check-label">You'll recognize the outfit</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q3" value="B">
<label class="form-check-label">The grim reaper will tell you</label>
</div>
</div>
<div class="my-5">
<p class="lead font-weight-normal">4. What's a ninja's favourite array method?</p>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q4" value="A" checked>
<label class="form-check-label">forEach()</label>
</div>
<div class="form-check my-2 text-white-50">
<input type="radio" name="q4" value="B">
<label class="form-check-label">slice()</label>
</div>
</div>
<div class="text-center">
<input type="submit" class="btn btn-light">
</div>
</form>
</div>
</div>
<script src="app.js"></script>
</body>
</html>

Categories

Resources