How Do I Make My Quiz Site Work? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi I made a quiz site and I can not make it display the answers I got correct and the image associated with the correct enough answers.
Here is my codepen: https://codepen.io/tovasfo/pen/veJdxd
<head>
<title>This quiz</title>
<link href="style.css" rel="stylesheet">
<script src="main.js"></script>
</head>
<body>
<h1>Short canadian quiz</h1>
<h2>If you cheat it will take longer</h2>
<form id="quiz" name="quiz">
<p class="questions">What is our national animal?</p>
<input type="radio" id="mc" name="q1" value="Bed">Bed<br>
<input type="radio" id="mc" name="q1" value="Beaver">Beaver<br>
<input type="radio" id="mc" name="q1" value="Bed">It's not this<br>
<!-- // the answer is Beaver -->
<p class="questions">What is our national sport?</p>
<input type="radio" id="mc" name="q2" value="Hockey">Hockey<br>
<input type="radio" id="mc" name="q2" value="Tag">Tag<br>
<input type="radio" id="mc" name="q2" value="Poutine">Poutine<br>
<!-- // Hockey -->
<p class="questions">How many points are on the maple leaf on the flag?</p>
<input type="radio" id="mc" name="q3" value="75">75<br>
<input type="radio" id="mc" name="q3" value="9">9<br>
<input type="radio" id="mc" name="q3" value="11">11<br>
<!-- // 11 -->
<p class="questions">What alcholic beverage do we consume the most?</p>
<input type="radio" id="mc" name="q4" value="Wine">Wine<br>
<input type="radio" id="mc" name="q4" value="Beer">Beer<br>
<input type="radio" id="mc" name="q4" value="Red Bull">Red Bull<br>
<!-- // Beer -->
<p class="questions">What is the capital of canada?</p>
<input type="radio" id="mc" name="q5" value="Toronto">Toronto<br>
<input type="radio" id="mc" name="q5" value="Ottawa">Ottawa<br>
<input type="radio" id="mc" name="q5" value="Your Wrong City">Your Wrong City<br>
<!-- // Ottawa -->
<p class="questions">What was invented by a canadian?</p>
<input type="radio" id="mc" name="q6" value="French Fries Baby">French Fries Baby<br>
<input type="radio" id="mc" name="q6" value="Basketball Baby">Basketball Baby<br>
<input type="radio" id="mc" name="q6" value="I'm Sorry">I'm Sorry<br>
<!-- // Basketball baby -->
<p><input id="button" type="button" value="submit" onclick="check();"></p>
</form>
<div id="done">
<p id="correct"></p>
<p id="message"></p>
</div>
</body>
</html>
CSS
body {
font-family: sans-serif, arial;
}
#done {
visibility: hidden;
}
JavaScript
function check() {
var q1 = document.quiz.q1.value;
var q2 = document.quiz.q2.value;
var q3 = document.quiz.q3.value;
var q4 = document.quiz.q4.value;
var q5 = document.quiz.q5.value;
var q6 = document.quiz.q6.value;
var correct = 0;
if (q1 == "Beaver") {
correct++;
}
if (q2 == "Hockey") {
correct++;
}
if (q3 == "11") {
correct++;
}
if (q4 == "Beer") {
correct++;
}
if (q5 == "Ottawa") {
correct++;
}
if (q6 == "Basketball baby") {
correct++;
}
var messages = [
"YOU ARE UNSTOPPABLE!!!",
"Excellent work",
"You got most",
"It's alright",
"It's not good ahhhhh",
"Don't try and act dumb",
"Your so drunk"
];
var pictures = [
"img/socol.gif",
"img/tenor.gif",
"img/mity.gif",
"img/okay.gif",
"img/ohno.gif",
"img/dumb.gif",
"img/drunky.gif"
];
var range;
if (correct > 5) {
range = 0;
}
if (correct > 4 && correct < 6) {
range = 1;
}
if (correct > 3 && correct < 5) {
range = 2;
}
if (correct > 2 && correct < 4) {
range = 3;
}
if (correct > 1 && correct < 3) {
range = 4;
}
if (correct > 0 && correct < 2) {
range = 5;
}
if (correct < 1) {
range = 6;
}
document.getElementById("done").style.visiblity = "visible";
document.getElementById("correct").innerHTML =
"you got " + correct + " correct.";
document.getElementById("message").innerHTML = messages[range];
document.getElementById("picture").src = pictures[range];
}
This is all I have for now. I just want the quiz to actually function by giving the user how many answers he or she got right and the correct image.

You must include you javascript file on the bottom of the page try this and is gonna work
index.html
<!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>
<h1>Short canadian quiz</h1>
<h2>If you cheat it will take longer</h2>
<form id="quiz" name="quiz">
<p class="questions">What is our national animal?</p>
<input type="radio" id="mc" name="q1" value="Bed">Bed<br>
<input type="radio" id="mc" name="q1" value="Beaver">Beaver<br>
<input type="radio" id="mc" name="q1" value="Bed">It's not this<br>
<!-- // the answer is Beaver -->
<p class="questions">What is our national sport?</p>
<input type="radio" id="mc" name="q2" value="Hockey">Hockey<br>
<input type="radio" id="mc" name="q2" value="Tag">Tag<br>
<input type="radio" id="mc" name="q2" value="Poutine">Poutine<br>
<!-- // Hockey -->
<p class="questions">How many points are on the maple leaf on the flag?</p>
<input type="radio" id="mc" name="q3" value="75">75<br>
<input type="radio" id="mc" name="q3" value="9">9<br>
<input type="radio" id="mc" name="q3" value="11">11<br>
<!-- // 11 -->
<p class="questions">What alcholic beverage do we consume the most?</p>
<input type="radio" id="mc" name="q4" value="Wine">Wine<br>
<input type="radio" id="mc" name="q4" value="Beer">Beer<br>
<input type="radio" id="mc" name="q4" value="Red Bull">Red Bull<br>
<!-- // Beer -->
<p class="questions">What is the capital of canada?</p>
<input type="radio" id="mc" name="q5" value="Toronto">Toronto<br>
<input type="radio" id="mc" name="q5" value="Ottawa">Ottawa<br>
<input type="radio" id="mc" name="q5" value="Your Wrong City">Your Wrong City<br>
<!-- // Ottawa -->
<p class="questions">What was invented by a canadian?</p>
<input type="radio" id="mc" name="q6" value="French Fries Baby">French Fries Baby<br>
<input type="radio" id="mc" name="q6" value="Basketball Baby">Basketball Baby<br>
<input type="radio" id="mc" name="q6" value="I'm Sorry">I'm Sorry<br>
<!-- // Basketball baby -->
<p><input id="button" type="button" value="submit" onclick="check();"></p>
</form>
<div id="done">
<p id="correct"></p>
<p id="message"></p>
</div>
<script src="./main.js"></script> <======= Heare
</body>
</html>
main.js
function check() {
var q1 = document.quiz.q1.value;
var q2 = document.quiz.q2.value;
var q3 = document.quiz.q3.value;
var q4 = document.quiz.q4.value;
var q5 = document.quiz.q5.value;
var q6 = document.quiz.q6.value;
var correct = 0;
if (q1 == "Beaver") {
correct++;
}
if (q2 == "Hockey") {
correct++;
}
if (q3 == "11") {
correct++;
}
if (q4 == "Beer") {
correct++;
}
if (q5 == "Ottawa") {
correct++;
}
if (q6 == "Basketball baby") {
correct++;
}
var messages = [
"YOU ARE UNSTOPPABLE!!!",
"Excellent work",
"You got most",
"It's alright",
"It's not good ahhhhh",
"Don't try and act dumb",
"Your so drunk"
];
var pictures = [
"img/socol.gif",
"img/tenor.gif",
"img/mity.gif",
"img/okay.gif",
"img/ohno.gif",
"img/dumb.gif",
"img/drunky.gif"
];
var range;
if (correct > 5) {
range = 0;
}
if (correct > 4 && correct < 6) {
range = 1;
}
if (correct > 3 && correct < 5) {
range = 2;
}
if (correct > 2 && correct < 4) {
range = 3;
}
if (correct > 1 && correct < 3) {
range = 4;
}
if (correct > 0 && correct < 2) {
range = 5;
}
if (correct < 1) {
range = 6;
}
document.getElementById("done").style.visiblity = "visible";
document.getElementById("correct").innerHTML =
"you got " + correct + " correct.";
document.getElementById("message").innerHTML = messages[range];
document.getElementById("picture").src = pictures[range];
}

Related

How do I check two options at once in the option quiz?

I did it as you wanted and it still doesn't work as it should, if I don't check anything in the checkbox and give it an "evaluate test" so it will write me 1 point anyway, which is wrong. Some ideas?
function check(){
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelectorAll('input[value="question2"]:checked', 'input[value="question2"]:checked');
var correct = 0;
if (question1 !=null && question1.value == " Červená, Zelená, Modrá") {
correct++;
}
if (question4 !=null &&question4.value == "Rastrová grafika","Vektorová grafika"){
correct++;
}
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
<form class="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value=" Červená, Zelená, Modrá"> Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value=" Červená, Zelená, Žlutá"> Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value=" Černá, Fialová, Modrá"> Červená, Fialová, Modrá<br>
</form>
<form class="quiz">
<p style="font-weight: 900">Způsoby jakým počítače ukládají a zpracovávají obrazové informace se nazývají? (Vyber dvě možnosti)</p>
<input type="checkbox" class='question2' name="question4" value=" 3D grafika"> 3D grafika<br>
<input type="checkbox" class='question2' name="question4" value=" Vektorová grafika"> Vektorová grafika<br>
<input type="checkbox" class='question2' name="question4" value=" Fotografika"> Fotografika<br>
<input type="checkbox" class='question2' name="question4" value=" Rastrová grafika"> Rastrová grafika<br>
</form>
<br>
<div id="number_correct"></div>
question2 needs to be the result of a call to querySelectorAll, not just querySelector. It will then be a list of all the checked elements (querySelector only returns the first matched element, no matter how many match the selector.
You would need to loop the list and see what it contains. You need to verify that only two boxes were checked, and that they were the correct ones.
Also in your code, the question4 variable isn't defined, and input[value="question2"]:checked will never match anything - there's no checkbox with that value, and looking for the value makes no sense anyway. Also your question2 checkboxes randomly had "question4" as their name. I've corrected those issues and a couple of other minor things.
Something like this will work better:
function check() {
var question1 = document.querySelector('input[name="question1"]:checked');
var question2 = document.querySelectorAll('input[name="question2"]:checked');
var correct = 0;
if (question1 != null && question1.value == "Červená, Zelená, Modrá") {
correct++;
}
var q2answers = ["Rastrová grafika", "Vektorová grafika"];
var correctQ2NumAnswers = (q2answers.length == question2.length);
var correctQ2AnswersCount = 0;
question2.forEach(function(el) {
if (q2answers.includes(el.value)) correctQ2AnswersCount++;;
});
if (correctQ2NumAnswers == true && correctQ2AnswersCount == q2answers.length) correct++;
document.getElementById("number_correct").innerHTML = "Máš " + correct + " otázky/otázek správně.";
}
document.querySelector("#check").addEventListener("click", check);
<form class="quiz">
<p style="font-weight: 900">V RGB modelu se jedná o jaké barvy?</p>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Modrá"> Červená, Zelená, Modrá<br>
<input type="radio" class='question1' name="question1" value="Červená, Zelená, Žlutá"> Červená, Zelená, Žlutá<br>
<input type="radio" class='question1' name="question1" value="Černá, Fialová, Modrá"> Červená, Fialová, Modrá<br>
</form>
<form class="quiz">
<p style="font-weight: 900">Způsoby jakým počítače ukládají a zpracovávají obrazové informace se nazývají? (Vyber dvě možnosti)</p>
<input type="checkbox" class='question2' name="question2" value="3D grafika"> 3D grafika<br>
<input type="checkbox" class='question2' name="question2" value="Vektorová grafika"> Vektorová grafika<br>
<input type="checkbox" class='question2' name="question2" value="Fotografika"> Fotografika<br>
<input type="checkbox" class='question2' name="question2" value="Rastrová grafika"> Rastrová grafika<br>
</form>
<br>
<div id="number_correct"></div>
<button type="button" id="check">
Check Answers
</button>

Trying to convert my JavaScript into JQuery

I'm trying to convert my Javascript code into JQuery but I know I did something wrong when calling the function. I'm having a tough time knowing exactly what to put when trying to call the radio elements by name.
Original Javascript works, but I'm not sure how to get the JQuery version to work.
Index HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script
</head>
<body>
<header><h1>Disney Quiz</h1></header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created?</p>
<input type="radio" name="question0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="question0" value="B">Donald Duck<br>
<input type="radio" name="question0" value="C">Mickey Mouse<br>
<input type="radio" name="question0" value="D">Goofy<br>
<p id="flag0"><p>
</section>
<section id="radio2">
<p> Question 2) Snow White was the first ____ to ever be produced successfully.</p>
<input type="radio" name="question1" value="A">Movie<br>
<input type="radio" name="question1" value="B">Live-Action<br>
<input type="radio" name="question1" value="C">Cel-animated Film<br>
<input type="radio" name="question1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<section id="radio3">
<p> Question 3) Walt left a big impression when he had created ____ films for the U.S. government</p>
<input type="radio" name="question2" value="A">Peacemaker<br>
<input type="radio" name="question2" value="B">Political<br>
<input type="radio" name="question2" value="C">World War II<br>
<input type="radio" name="question2" value="D">Religious<br>
<p id="flag2"><p>
</section>
<section id="radio4">
<p> Question 4) Which of the following is true?</p>
<input type="radio" name="question3" value="A">Disney at first wanted to become a filmmaker<br>
<input type="radio" name="question3" value="B">Disney has made multiple controversial cartoons.<br>
<input type="radio" name="question3" value="C">Disney holds the record for most individual Oscar wins.<br>
<input type="radio" name="question3" value="D">Heart failure was the cause of Disney's death.<br>
<p id="flag3"><p>
</section>
<section id="radio5">
<p> Question 5) Which of the following has been rumored to happen to Walt Disney after his death?</p>
<input type="radio" name="question4" value="A">Faked his death<br>
<input type="radio" name="question4" value="B">Cremated<br>
<input type="radio" name="question4" value="C">Buried<br>
<input type="radio" name="question4" value="D">Cryogenically frozen<br>
<p id="flag4"><p>
</section>
<br>
<button type="button">Show Results</button>
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
Original JavaScript
var answers = ["A","C","B","C","D"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
return radios[y].value;
}
}
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else if(getCheckedValue("question"+i) != answers[i])
{
document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore()
{
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
JQuery
var answers = ["A","C","B","C","D"],
total = answers.length;
$(function getCheckedValue()
{
var radios = $('[name="question"]');
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
return radios[y].value;
}
}
});
$(':button').on('click', function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
$("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else if(getCheckedValue("question"+i) != answers[i])
{
$("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
});
$(function returnScore()
{
var x = $("myText").value;
$("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
});
You don't need to put function definitions inside $(...), just put it at top-level just like in your plain JS version. $(...) is for code that needs to run after the DOM is loaded, but you don't need to wait to define functions. It will also call the functions you define there, not just define them.
The jQuery version of getCheckValue() isn't using the parameter, you need to add that.
And selectors for IDs need to begin with #.
function getCheckedValue(radioname)
{
return $(`[name="${radioname}"]:checked:first`).val();
}
In getScore your else if condition is the opposite of the if condition. So you should just use else. And jQuery uses the .html() and .text() functions to fill in an element, you don't assign to .innerHTML.
$(':button').on('click', function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
$("flag"+i).innerHTML = "";
if(getCheckedValue("question"+i) == answers[i])
{
score += 1;
}
else
{
$("#flag"+i).text("Your answer is incorrect.");
}
}
return score;
});
function returnScore()
{
var x = $("#myText").value;
$("#results").html(x + ", your score is " + getScore() + "/" + total);
}
In the HTML, you need to change the order that you load the scripts:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="scripts/quiz.js"></script>
Since quiz.js uses jQuery, jQuery has to be loaded first.

Grading a test - Loop checking radio input values (JS)

I am working on an online test where you get your output directly. I get stuck at checking the values of the radio input with a loop. Why gives the checkFields function output undefined?
Javascript Code:
<script type="text/javascript">
$(document).ready(function(){
//click button
$("#submitTest").click(function(){
//check if all answers are given
for (i = 1; i <= 10; i++) {
if (checkFields([i].toString())) {
//calculate total score
if ($("input[name=[i]]").val() == aq[i]) {score = score + 1};
}
else{alert("Please answer all questions");
break}};
console.log(score);
//return level of English
}
)
//setFunction
function checkFields(Q){
console.log(
$("[name='[Q]']:checked").val())
}
//Set score 0
var score = 0;
//Answers
var aq1 = "a1";
var aq2 = "a1";
var aq3 = "a3";
var aq4 = "a2";
var aq5 = "a1";
var aq6 = "a2";
var aq7 = "a3";
var aq8 = "a3";
var aq9 = "a1";
var aq10 = "a1";
}
)
</script>
HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- liberaries -->
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<!-- Form -->
<form id="testEnglish">
<!-- Q1 -->
<p class="question">1. Can I park here?</p>
<input type="radio" id="1" name="1" value="a1">a1<br>
<input type="radio" id="1" name="1" value="a2">a2<br>
<input type="radio" id="1" name="1" value="a3">a3
<!-- Q2 -->
<p class="question">2. Can I park here?</p>
<input type="radio" name="2" value="a1">a1<br>
<input type="radio" name="2" value="a2">a2<br>
<input type="radio" name="2" value="a3">a3
<!-- Q3 -->
<p class="question">3. Can I park here?</p>
<input type="radio" name="3" value="a1">a1<br>
<input type="radio" name="3" value="a2">a2<br>
<input type="radio" name="3" value="a3">a3
<!-- Q4 -->
<p class="question">4. Can I park here?</p>
<input type="radio" name="4" value="a1">a1<br>
<input type="radio" name="4" value="a2">a2<br>
<input type="radio" name="4" value="a3">a3
<!-- Q5 -->
<p class="question">5. Can I park here?</p>
<input type="radio" name="5" value="a1">a1<br>
<input type="radio" name="5" value="a2">a2<br>
<input type="radio" name="5" value="a3">a3
<!-- Q6 -->
<p class="question">6. Can I park here?</p>
<input type="radio" name="6" value="a1">a1<br>
<input type="radio" name="6" value="a2">a2<br>
<input type="radio" name="6" value="a3">a3
<!-- Q7 -->
<p class="question">7. Can I park here?</p>
<input type="radio" name="7" value="a1">a1<br>
<input type="radio" name="7" value="a2">a2<br>
<input type="radio" name="7" value="a3">a3
<!-- Q8 -->
<p class="question">8. Can I park here?</p>
<input type="radio" name="8" value="a1">a1<br>
<input type="radio" name="8" value="a2">a2<br>
<input type="radio" name="8" value="a3">a3
<!-- Q9 -->
<p class="question">9. Can I park here?</p>
<input type="radio" name="9" value="a1">a1<br>
<input type="radio" name="9" value="a2">a2<br>
<input type="radio" name="9" value="a3">a3
<!-- Q10 -->
<p class="question">10. Can I park here?</p>
<input type="radio" name="10" value="a1">a1<br>
<input type="radio" name="10" value="a2">a2<br>
<input type="radio" name="10" value="a3">a3
</form>
<!-- Submit -->
<button id="submitTest">Submit Test!</button>
</body>
</html>
This code might not be the way to do it. I tried various ways but did not manage.
edited below
New code
https://jsfiddle.net/5fnugrts/#&togetherjs=AOK0k8r4i2
HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Libaries -->
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<!-- Form -->
<form id="testEnglish">
<div id="myForm"></div>
</form>
<!-- Submit button -->
<button id="submitTest">Submit Test!</button>
Javascript Code
<!-- JS -->
<script type="text/javascript">
$(document).ready(function() {
//Answers and Questions constructor ("question","answer1","answer2","answer3","a"+number of correct answer)
function Question(question, answer1, answer2, answer3, correctAnswer) {
this.q = question;
this.a1 = answer1;
this.a2 = answer2;
this.a3 = answer3;
this.ca = correctAnswer;
};
//Answers and Questions ("question","answer1","answer2","answer3","a"+number of correct answer)
var aQ = {
Q1: new Question("What is the correct answer 1?", "Cheese", "Ham", "Turkey", "a1"),
Q2: new Question("What is the correct answer 2?", "Cheese", "Ham", "Turkey", "a1"),
Q3: new Question("What is the correct answer 3?", "Cheese", "Ham", "Turkey", "a2"),
Q4: new Question("What is the correct answer 4?", "Cheese", "Ham", "Turkey", "a2"),
Q5: new Question("What is the correct answer 5?", "Cheese", "Ham", "Turkey", "a3"),
};
//Set Setinhtml function ("name of radio group" "question","answer1","answer2","answer3","a"+number of correct answer)
function appendQuestion(groupName, question, answer1, answer2, answer3) {
$("div#myForm").append("<p class=\"question\">" + question + "</p>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a1\">" + answer1 + "<br>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a2\">" + answer2 + "<br>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a3\">" + answer3 + "<br>")
};
//Set in HTML loop
for (i = 1; i <= Object.keys(aQ).length; i++) {
appendQuestion([i],
eval("aQ.Q" + [i] + ".q"),
eval("aQ.Q" + [i] + ".a1"),
eval("aQ.Q" + [i] + ".a2"),
eval("aQ.Q" + [i] + ".a3"),
eval("aQ.Q" + [i] + ".ca"))
};
//Sumbit answers
$("#submitTest").click(function() {
score = 0
//Loop and give values
for (i = 1; i <= Object.keys(aQ).length; i++) {
tAnswer = $("input:radio[name ='" + i + "']:checked").val()
cAnswer = eval("aQ.Q" + i + ".ca")
//Check if answers are filled in
if (!tAnswer) {
alert("Please answer all questions");
return;
}
//Check correct answers
else if (tAnswer == cAnswer) {
score++
}
}
//Report score
alert("Your score is " + score + "/" + Object.keys(aQ).length);
});
});
</script>
I tweaked your code to make it more compact and effecient
Here's a codepen
$(document).ready(function() {
//Set score 0
var score = 0;
//Answers
aq1 = "a1";
aq2 = "a1";
aq3 = "a3";
aq4 = "a2";
aq5 = "a1";
aq6 = "a2";
aq7 = "a3";
aq8 = "a3";
aq9 = "a1";
aq10 = "a1";
$("#submitTest").click(function() {
score = 0
for (i = 1; i <= 10; i++) {
tAnswer = $("input:radio[name ='" + i + "']:checked").val()
cAnswer = window["aq"+i]
if (!tAnswer) {
alert("Please answer all questions");
return;
} else if (tAnswer == cAnswer) {
console.log("#"+i+": correct")
score++
} else if (tAnswer != cAnswer) {
console.log("#"+i+" incorrect")
}
}
alert("Your score is "+ score +"/10");
});
});
tAnswer is the answer and cAnswer is the correct answer, you can also check if(!cAnswer) then you didn't define the correct answer.

how can i call a function from another js file

How can I get the same result after quiz ends without clicking the Results button
Here is what I've tried
if (currentQuestion == totalQuestions) {
var outputDiv = document.getElementById("quizEnds");
outputDiv.innerHTML = "You have reached the final question.";
$('#next').remove();
getScore(this.form);
}
it does not work. can someone point out the error please. it has to be two separated files. thanks
//quizeffect.js
var totalQuestions = $('.questions').size();
var currentQuestion = 0;
$questions = $('.questions');
$questions.hide();
$($questions.get(currentQuestion)).fadeIn();
$('#next').click(function () {
$($questions.get(currentQuestion)).fadeOut(function () {
currentQuestion = currentQuestion + 1;
if (currentQuestion == totalQuestions) {
var outputDiv = document.getElementById("quizEnds");
outputDiv.innerHTML = "<h2>You have reached the final question.</h2>";
$('#next').remove();
getScore(this.form);
} else {
$($questions.get(currentQuestion)).fadeIn();
}
});
});
//tlcquizzapp.js
/*====================app js====================*/
var numberOfQuestions = 6;
// Insert number of choices in each question
var numberOfChoices = 4;
var rightAnswers = 0;
var correct = [];
var wrong =[];
var answers = new Array("Double Parking",
"The aplicant will have the aplication denied", "Never", "All of the above",
"Yellow taxi medallion base", "You are allowed to pick up in the crosswalk if the passenger is standing at the intersection");
function print(message) {
var outputDiv = document.getElementById("output");
outputDiv.innerHTML = message;
}
function buildList(arr) {
var listHTML = '<ol>';
for (var i = 0; i < arr.length; i++) {
listHTML += '<li>' + arr[i] + '</li>';
}
listHTML += '</ol>';
return listHTML;
}
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i = 0; i < numberOfQuestions; i++) {
currElt = i * numberOfChoices;
for (j = 0; j < numberOfChoices; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
correct.push(currSelection.value);
}
else{
wrong.push(currSelection.value);
}
}
}
}
score = Math.round(score/numberOfQuestions*100);
var userAnswers = '<p>You got ' + score + ' % on your test.</p>';
userAnswers += '<h2>You got these answers correct:</h2>';
userAnswers += buildList(correct);
userAnswers += '<h2>You got these answers wrong</h2>';
userAnswers += buildList(wrong);
print(userAnswers);
}
.questions p{
font-size: 24px;
background-color: #3399FF;
color: #FFF;
padding: 20px;
}
.options li{
font-size: 18px;
}
form {
width: 80%;
margin: 0 auto;
border: 1px solid #DDD;
}
button {
border: none;
padding: 10px;
border-radius: 10px;
background-color: #3399FF;
color: #FFF;
}
button:hover {
background-color: orange;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TLC Driver Practice Quiz</title>
<link rel="stylesheet" href="css/tlc-style.css">
</head>
<body>
<div><h1>TLC Practice Quiz</h1></div>
<form>
<div class="questions">
<p>1. Which of the following is not a moving violation?</p>
<ol type="A" class="options">
<li><input class="option" type="radio" name="q1" value="Double Parking">Double Parking</li>
<li><input class="option" type="radio" name="q1" value="Tailgating">Tailgating</li>
<li><input class="option" type="radio" name="q1" value="Speeding">Speeding</li>
<li><input class="option" type="radio" name="q1" value="Failing to signal a turn">Failing to signal a turn</li>
</ol>
</div>
<div class="questions">
<p>2. What is the penalty for an aplicant of an TLC driver's license who test positive for drugs and fails the drug test?</p>
<ol type="A" class="options">
<li><input class="option" type="radio" name="q2" value="The aplicant must take the test again">The aplicant must take the test again</li>
<li><input class="option" type="radio" name="q2" value="The aplicant will have a provationary license">The aplicant will have a provationary license</li><li><input class="option" type="radio" name="q2" value="The aplicant will have the aplication denied">The aplicant will have the aplication denied</li>
<li><input class="option" type="radio" name="q2" value="The aplicant will have to drive carfolly">The aplicant will have to drive carfolly</li>
</ol>
</div>
<div class="questions">
<p>3. In wich situation may you pass a school bus with the red flashing light on?</p>
<ol type="A" class="options">
<li><input class="option" type="radio" name="q3" value="When it is snowing">When it is snowing</li>
<li><input class="option" type="radio" name="q3" value="When you do not see children around">When you do not see children around</li>
<li><input class="option" type="radio" name="q3" value="When someon behind beeps the horn">When someon behind beeps the horn</li>
<li><input class="option" type="radio" name="q3" value="Never">Never<br/>
</ol>
</div>
<div class="questions">
<p>4. Wich of the following is a service animal?</p>
<ol type="A" class="options">
<li><input class="option" type="radio" name="q4" value="A seeing eye dog">A seeing eye dog</li>
<li><input class="option" type="radio" name="q4" value="A guide dog">Aguide dog</li>
<li><input class="option" type="radio" name="q4" value="A signal dog">A signal dog</li>
<li><input class="option" type="radio" name="q4" value="All of the above">All of the above</li>
</ol>
</div>
<div class="questions">
<p>5. Which of the following is not a For-Hire base?</p>
<ol type="A" class="options">
<li><input class="option" type="radio" name="q5" value="Yellow taxi medallion base">Yellow taxi medallion base</li>
<li><input class="option" type="radio" name="q5" value="Black car base">Black car base</li>
<li><input class="option" type="radio" name="q5" value="Livery car service base station">Livery car service base station</li>
<li><input class="option" type="radio" name="q5" value="Luxury limousine base">Luxury limousine base</li>
</ol>
</div>
<div class="questions">
<p>6. Wich of the following is not correct?</p>
<ol type="A" class="options">
<li><input class="option" type="radio" name="q6" value="When you pick up a passenger, the vehicle should be 12 inches from yhe curb">When you pick up a passenger, the vehicle should be 12 inches from yhe curb</li>
<li><input class="option" type="radio" name="q6" value="When you pick up a passenger, the vehicle should be parallel to the curb">When you pick up a passenger, the vehicle shouldbe parallel to the curb</li>
<li><input class="option" type="radio" name="q6" value="If the passenger is waiting next to a car that is already parked, you should look for space within 100 ft.">If the passenger is waiting next to a car that is already parked, you should look for space within 100 ft.</li>
<li><input class="option" type="radio" name="q6" value="You are allowed to pick up in the crosswalk if the passenger is standing at the intersection">You are allowed to pick up in the crosswalk if the passenger is standing at the intersection</li>
</ol>
</div>
<div id="quizEnds"></div>
<button type="button" name="nextButton" id='next' value="Next">Next</button>
<button class="results" type="button" value="Results" onClick="getScore(this.form);">Results</button>
<!-- <button type="reset" value="Clear Answers">Clear Answers</button> -->
<div id="output"></div>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/tlcquizzapp.js"></script>
<script type="text/javascript" src="js/quizeffect.js"></script>
</body>
</html>
this is the button. Use closest() to traverse to the form it is within
Try
getScore($(this).closest('form')[0]);
Or simpler, give the form an id
<form id="myForm>
And use that id to target form
getScore($('#myForm')[0]);
You need to pass the form element to your getScore() function, but this.form does not represent the form element at that place in the code because it is inside the callback function passed to $questions.get(currentQuestion)).fadeOut(). At that point this refers to the question element. And even if you had a reference to the button element at that point, you could not get the form from it because the button has been removed from the page.
You could keep a reference to the form element in a variable where this does refer to the button element:
$('#next').click(function () {
var form = this.form;
And then use that when calling getScore():
getScore(form);
Inside a jQuery event function this refers to the element that the event is wired to. You therefore need to refer to the document.form[0], or use a jQuery version of the same.

Javascript help, randomizing quiz questions

i made some code recently but im wondering how to make the quiz choose 3 questions out of 6 instead of displaying 6 straight away. Help would be appreciated. I want the quiz to choose 3 questions at random, then if its reloaded have a chance to choose another 3 questions, out of a total pool of 6.
<script language="JavaScript">
var numQues = 6;
var numChoi = 3;
var answers = new Array(6);
answers[0] = "16";
answers[1] = "8";
answers[2] = "The Walking Dead";
answers[3] = "Batman v Superman";
answers[4] = "Tupac";
answers[5] = "#ATAME2016";
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;
}
</script>
</head>
<body>
<form name="quiz">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
<p>
2. How many pages are on this website?<br>
<input type="checkbox" name="q2" value="8">8<br>
<input type="checkbox" name="q2" value="6">6<br>
<input type="checkbox" name="q2" value="7">7<br>
<p>
3. What's the most popular show this week?<br>
<input type="checkbox" name="q3" value="The Walking Dead">The Walking Dead<br>
<input type="checkbox" name="q3" value="Mandem on the wall">Mandem on the wall<br>
<input type="checkbox" name="q3" value="Cotchin with Ksara">Cotchin with Ksara<br>
<p>
4. What movie has made the most money this week in the box office?<br>
<input type="checkbox" name="q4" value="Ride along 2">Ride along 2<br>
<input type="checkbox" name="q4" value="Batman v Superman">Batman v Superman<br>
<input type="checkbox" name="q4" value="GasMan">GasMan<br>
<p>
5. Which star in the celebrity page is no longer alive?<br>
<input type="checkbox" name="q5" value="Tupac">Tupac<br>
<input type="checkbox" name="q5" value="50 Cent">50 Cent<br>
<input type="checkbox" name="q5" value="Bradley cooper">Bradley cooper<br>
<p>
6. What is our twitter account name (#)?<br>
<input type="checkbox" name="q6" value="#ATAME">#ATAME<br>
<input type="checkbox" name="q6" value="#ATAME2016">#ATAME2016<br>
<input type="checkbox" name="q6" value="#A2THETAME">#A2THETAME<br>
<p>
<input type="button" value="Get score" onClick="getScore(this.form)">
<input type="reset" value="Clear"><p>
Score = <input type=text size=15 name="percentage"><br>
Correct answers:<br>
<textarea name="solutions" wrap="virtual" rows="4" cols="40"></textarea>
</form>
</div>
You'll want to use a Math.random() function. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
A common example is found at: http://www.w3schools.com/jsref/jsref_random.asp
I'd try something like this, using jQuery:
// Hides all questions on page load.
$('.questions').hide();
// Randomly shows 3 questions.
for (var i=0; i<3; i++) {
var questionId = Math.floor((Math.random() * 6) + 1);
$('#question-' + questionId).show();
}
Then wrap your questions in wrapping <div> or <p> tags like this:
<div id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</div>
Or this:
<p id="question-1" class="questions">
1. How many movie trailers are on the movie page?<br>
<input type="checkbox" name="question1" value="10">10<br>
<input type="checkbox" name="question1" value="14">14<br>
<input type="checkbox" name="question1" value="16">16<br>
</p>

Categories