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.
Related
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.
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];
}
I am working to create a quiz. and I want to add the option for all the people that has 60% or more to have a congratilation message and to show a link to another web page were they can go and fill a form. For 60% or less just to show a sorry message.
Below is my sample code for my quiz. (this has only 2 questions FYI)
Thanks :
var numQues = 2;
var numChoi = 3;
var answers = new Array(2);
answers[0] = "Answer 1-1";
answers[1] = "Answer 2-1";
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;
}
<form name="quiz">
1. Question 1<br>
<input type="radio" name="q1" value="Answer 1-1">Answer 1-1<br>
<input type="radio" name="q1" value="Answer 1-2">Answer 1-2<br>
<input type="radio" name="q1" value="Answer 1-3">Answer 1-3<br>
<p>
2. Question 2<br>
<input type="radio" name="q2" value="Answer 2-1">Answer 2-1<br>
<input type="radio" name="q2" value="Answer 2-2">Answer 2-2<br>
<input type="radio" name="q2" value="Answer 2-3">Answer 2-3<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>
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>
I'm working on a restaurant menu and with this I've create burgers, fries, and drinks as check boxes. when you click on burgers or fries or drinks options appear for you to choose from like a burger with cheese or a burger plain or with bacon or with both is available. Also with fries you can choose small medium or large and drinks have soda or bottled water. My question was how to compute the total of said items
Burgers
Regular (4.19)
w/ Cheese (4.79)
w/ Bacon (4.79)
w/ Bacon and Cheese (5.39)
Fries
Small (2.39)
Medium (3.09)
Large (4.99)
Drinks
Soda (1.69)
Bottled Water (1.49)
and with the advice I received I created this with the desire result I was seeking.
<!DOCTYPE html>
<html>
<head>
<title>Restaurant Menu</title>
</head>
<body>
<div class="page">
<div class="topbar">
Menu
</div>
<div class="row">
<!--Burgers CheckBox-->
<div class="cell">
<input type="checkbox" name="chkBurgers" id="chkBurgers" /><label
for="chkBurgers">Burgers</label>
</div>
<!--Cell Containing Burger Menu-->
<div class="cell" id="divBurgers" style="visibility:hidden;">
<input type="radio" name="radBurgers" id="radBurgerRegular" value="4.19" /><label
for="radBurgerRegular">Regular (4.19)</label><br />
<input type="radio" name="radBurgers" id="radBurgerCheese" value="4.79" /><label
for="radBurgerCheese">w/ Cheese (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBacon" value="4.79" /><label
for="radBurgerBacon">w/ Bacon (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBaconCheese" value="5.39" /><label
for="radBurgerBaconCheese">w/ Bacon and Cheese (5.39)</label><br />
</div>
</div>
<div class="clear"></div>
<div class="row">
<!--Fries CheckBox-->
<div class="cell">
<input type="checkbox" name="chkFries" id="chkFries" /><label
for="chkFries">Fries</label>
</div>
<!--Cell Containing Fries Menu-->
<div class="cell" id="divFries" style="visibility:hidden;">
<input type="radio" name="radFries" id="radFriesSmall" value="2.39" /><label
for="radFriesSmall">Small (2.39)</label><br />
<input type="radio" name="radFries" id="radFriesMedium" value="3.09" /><label
for="radFriesMedium">Medium (3.09)</label><br />
<input type="radio" name="radFries" id="radFriesLarge" value="4.99" /><label
for="radFriesSmall">Large (4.99)</label><br />
</div>
</div>
<div class="clear"></div>
<div class="row">
<!--Drinks CheckBox-->
<div class="cell">
<input type="checkbox" name="chkDrinks" id="chkDrinks" /><label
for="chkDrinks">Drinks</label>
</div>
<!--Cell Containing Drink Menu-->
<div class="cell" id="divDrinks" style="visibility:hidden;">
<input type="radio" name="radDrinks" id="radDrinkSoda" value="1.69" /><label
for="radDrinkSoda">Soda (1.69)</label><br />
<input type="radio" name="radDrinks" id="radDrinkWater" value="1.49" /><label
for="radDrinkWater">Bottled Water (1.49)</label><br />
</div>
<!--Cell Containing Compute Button and Total Field-->
<div class="cell" style="float:right;">
Total Meal Cost: <input type="text" name="txtTotal" id="txtTotal" /><br /><br />
<button id="btnCompute" name="btnCompute">Compute Total</button>
</div>
</div>
<div class="clear"></div>
</div>
<link rel="stylesheet" type="text/css" href="week11.css">
<script src="week11.js"></script>
</body>
</html>
Javascript:
var total = parseFloat(document.getElementById('txtTotal').value);
function ToggleBurgers() {
var chkBurgers = document.getElementById('chkBurgers');
var burgers = document.getElementById('divBurgers');
if (chkBurgers.checked) {
burgers.style.visibility = 'visible';
} else {
burgers.style.visibility = 'hidden';
}
}
function ToggleFries() {
var chkFries = document.getElementById('chkFries');
var fries = document.getElementById('divFries');
if (chkFries.checked) {
fries.style.visibility = 'visible';
} else {
fries.style.visibility = 'hidden';
}
}
function ToggleDrinks() {
var chkDrinks = document.getElementById('chkDrinks');
var drinks = document.getElementById('divDrinks');
if (chkDrinks.checked) {
drinks.style.visibility = 'visible';
} else {
drinks.style.visibility = 'hidden';
}
}
function ComputeTotal() {
var total = 0;
if(document.getElementById('chkBurgers').checked){
if(document.getElementById('radBurgerRegular').checked){
total += 4.19;
}
if(document.getElementById('radBurgerCheese').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBacon').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBaconCheese').checked){
total += 5.39;
}
}
if(document.getElementById('chkFries').checked){
if(document.getElementById('radFriesSmall').checked){
total += 2.39;
}
if(document.getElementById('radFriesMedium').checked){
total += 3.09;
}
if(document.getElementById('radFriesLarge').checked){
total += 4.99;
}
}
if(document.getElementById('chkDrinks').checked){
if(document.getElementById('radDrinkSoda').checked){
total += 1.69;
}
if(document.getElementById('radDrinkWater').checked){
total += 1.49;
}
}
document.getElementById('txtTotal').value = total;
}
function init() {
var chkBurgers = document.getElementById('chkBurgers');
chkBurgers.onchange = ToggleBurgers;
var chkFries = document.getElementById('chkFries');
chkFries.onchange = ToggleFries;
var chkDrinks = document.getElementById('chkDrinks');
chkDrinks.onchange = ToggleDrinks;
var btnCompute = document.getElementById('btnCompute');
btnCompute.onclick = ComputeTotal;
}
window.onload = init;
I think this question is OK for Stack. It's a bit tutorialy, but at least code has been provided, etc...
Anyway, on with the code:
function ComputeTotal() {
var total = 0;
if(document.getElementById('chkBurgers').checked){
if(document.getElementById('radBurgerRegular').checked){
total += 4.19;
}
if(document.getElementById('radBurgerCheese').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBacon').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBaconCheese').checked){
total += 5.39;
}
}
if(document.getElementById('chkFries').checked){
// -- etc. etc.
}
// -- etc. etc.
document.getElementById('txtTotal').value = total;
}
You could improve the code by setting the "value" of the radio button to be the price. e.g.
<input type="radio" name="radBurgers" id="radBurgerRegular" value="4.19" /><label for="radBurgerRegular">Regular (4.19)</label>
You could then just do something like:
total += document.getElementById('radBurgerRegular').checked ? parseFloat(document.getElementById('radBurgerRegular').value) : 0;
for each radio button.
You could even wrap that up in a function, something like:
total += addValueOf('radBurgerRegular'); // -- for each line
and set the function to be:
function addValueOf(elementId){
return document.getElementById(elementId).checked ? parseFloat(document.getElementById(elementId).value : 0;
}
You could definitely write it quicker, neater, better and prettier with jQuery, but it's good to learn the building blocks first -- keep it up!