/    Sign up×
Community /Pin to ProfileBookmark

Need help with JS quiz

Thank you for reading this!
I am developing a nonsensical quiz ( I used some existing code for my base) in an effort to teach myself JavaScript. I am currently having a couple of issues and would love some help.

First of all, I want to validate that each question has been answered – is there a way to do this? Also, there are a couple of questions that I would like users to be able to choose more than one answer.

Thanks in advance!
Here is my working site: [URL=”http://www.public.asu.edu/~srempel/quiz.html”]My quiz[/URL] where you can see the code and how it works as of now.

Again, any suggestions would be appreciated!

to post a comment
JavaScript

10 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERApr 16.2009 — There is a way to validate each question. I would set up a function to test the value != '' for textbox and drop-down selects, checked==true for checkboxes, and options validation for radio buttons. Do you know how to do each of these?

For the multiple answers: Do you want this applied to checkboxes or multiple selections of a drop-down box?

Finally, do you want to modify your existing code or are you in the mood for improvements?
Copy linkTweet thisAlerts:
@neptunegirlauthorApr 16.2009 — I would definitely be in the mood for improvements!


I only have two questions that I want multiple answers for, and they are both check boxes.


Thanks so much for responding!
Copy linkTweet thisAlerts:
@JMRKERApr 16.2009 — As the 'Terminator' might say: "I'll be back!" ?
Copy linkTweet thisAlerts:
@neptunegirlauthorApr 17.2009 — That made me smile. ?
Copy linkTweet thisAlerts:
@JMRKERApr 17.2009 — I haven't finished checking out all possible entries/responses

but I thought I might leave something for you to do. ?

Take a look at the following two files: Quiz.html and Quiz.js

There are only 5 questions, but they demonstrate the radio button, select box and multiple checkbox functions.

See if you can figure out what I have done and let me know if you have any questions.

Numerous quizzes could be created just by changing the Quiz.js to Quiz1.js, Quiz2.js, etc.

Quiz.html
<i>
</i>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;style type="text/css"&gt;
.style1 {font-family: "Trebuchet MS"}
&lt;/style&gt;
&lt;title&gt;Project 9 Quiz&lt;/title&gt;
&lt;script type="text/javascript" src="Quiz.js"&gt;&lt;/script&gt;

&lt;script language="javascript" type="text/javascript"&gt;
//This script is inspired by http://www.gamarod.com.ar - I used it as a jumping off point for my quiz.
// This portion defines the answers to the questions.
// Extensively modified
var done = new Array;
var yourAns = new Array;
var score = 0;

function getRBtnName(GrpName) {
var sel = document.getElementsByName(GrpName);
var fnd = -1;
var str = '';
for (var i=0; i&lt;sel.length; i++) {
if (sel[i].checked == true) { str = sel[i].value; fnd = i; }
}
// return fnd; // return option index of selection
// comment out next line if option index used in line above <br/>
return str;
}

function StatusAllCheckboxes(IDS,cnt) {
var str = '';
IDS = 'q'+IDS;
var tmp = '';
for (var i=0; i&lt;cnt; i++) {
tmp = document.getElementById(IDS+'_'+i);
if (tmp.checked) { str += tmp.value + '|'; }
}
return str; <br/>
}

// function Engine(question, answer, opt, Qtype) {
function Engine(question, answer, Qtype) {
switch (Qtype) {
case "RB" : yourAns[question] = answer; break;
case "SB" : yourAns[question] = answer; break;
default : yourAns[question] = ''; alert('Invalid question type: '+Qtype); break;
}
}

function EngineCB(question, answer, itemcnt) { // answer is not used at this time
yourAns[question] = StatusAllCheckboxes(question,itemcnt); <br/>
// alert('question: '+question+' :'+yourAns[question]);
}

//This is the code that calculates the score.
function Score(){
score = 0;
var tmp = '';
var answerText = "How awesome are you?&lt;p&gt;"; // alert('Size of QR: '+QR.length);
for (var i=1; i&lt;QR.length; i++) {
answerText = answerText+"&lt;br&gt;Question :"+i+" Your answer: "+yourAns[i]+"&lt;br&gt;";

<i> </i>tmp = QR[i][3];
<i> </i>if (QR[i][0] == 'CB') { tmp = tmp+'|'; }
// alert(i+' : '+tmp+' : '+yourAns[i]+'nn'+answerText+'nn');

<i> </i>if (tmp != yourAns[i]) {
<i> </i> answerText = answerText+"&lt;br&gt;The correct answer was "+QR[i][3]+"&lt;br&gt;"+explainAnswer[i]+"&lt;br&gt;";
<i> </i>} else {
<i> </i> answerText = answerText+" &lt;br&gt;Wooohooo! You got this one right! &lt;br&gt;";
<i> </i> score++;
<i> </i>}
}

answerText=answerText+"&lt;br&gt;&lt;br&gt;Your total score is : "+score+" out of "+(QR.length-1)+"&lt;br&gt;";

// for varying number of questions, alter scoring
var ScoreMax = QR.length-1;
var ScoreInc = Math.floor(ScoreMax / 4); // Don't have fewer than 5 questions.

answerText=answerText+"&lt;br&gt;Comment : ";
if(score&lt;=ScoreInc){ answerText=answerText+"It seems as if you need to study your useless trivia a bit more."; }
if(score&gt;=(ScoreInc+1) &amp;&amp; score &lt;=(ScoreInc*2)){ answerText=answerText+"Almost average."; }
if(score&gt;=(ScoreInc*2+1) &amp;&amp; score &lt;=(ScoreInc*3)){ answerText=answerText+"Hey, pretty good job."; }
if(score&gt;(ScoreInc*3+1)){ answerText=answerText+"You are the master of all!"; }

var w = window.open('', '', 'height=500,width=750,scrollbars');
w.document.open();
w.document.write(answerText);
w.document.close();
}
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;&lt;hr&gt;&lt;/p&gt;

&lt;p class="style1 style1"&gt;&lt;strong&gt;Section Two - Quiz:&lt;/strong&gt;&lt;/p&gt;
&lt;p class="style1 style1"&gt;All questions must be answered in order to calculate your score.&lt;/p&gt;
&lt;form name="myform" class="style1"&gt;
&lt;ol&gt;
&lt;script type="text/javascript"&gt;
var str = '';
var tmpr = [];
var resp = ['a','b','c','d','e','f','g','h','i','j']; // allows for up to 10 responses (can have more)
for (q=1; q&lt;QR.length; q++) {
str += '&lt;li&gt;'+QR[q][1]+'&lt;/li&gt;&lt;br /&gt;';
tmpr = QR[q][2].split('|');
switch (QR[q][0]) {
case 'RB' :
for (var r=0; r&lt;tmpr.length; r++) {
str += '&lt;input type="radio" name="q'+q+'" value="'+resp[r]+'"';
str += ' onClick="Engine('+q+',this.value,''+QR[q][0]+'')"&gt;';
str += resp[r]+'&amp;nbsp;&amp;nbsp;'+tmpr[r]+'&lt;br /&gt;';
} break;
case 'CB' :
for (var r=0; r&lt;tmpr.length; r++) {
str += '&lt;input type="checkbox" id="q'+q+'_'+r+'" name="q'+q+'" value="'+resp[r]+'"';
str += ' onClick="EngineCB('+q+',this.value,'+tmpr.length+')"&gt;';
str += resp[r]+'&amp;nbsp;&amp;nbsp;'+tmpr[r]+'&lt;br /&gt;';
} break;
case 'SB' :
str += '&lt;select name="q'+q+'" size="1" id="q'+q+'"';
str += ' onClick="Engine('+q+',this.value,''+QR[q][0]+'')"&gt;';
for (var r=0; r&lt;tmpr.length; r++) {
str += '&lt;option value="'+resp[r]+'"&gt;';
str += tmpr[r]+'&lt;/option&gt;';
} str += '&lt;/select&gt;'; break;

/* test code for future entries -- not implemented yet
case 'CBM' : break;
case 'SBM' :
str += '&lt;select name="q'+q+'" size="1" id="q'+q+'"';
str += ' onClick="Engine('+q+',this.value,''+QR[q][0]+'')" multiple&gt;';
for (var r=0; r&lt;tmpr.length; r++) {
str += '&lt;option name="q'+q+'" value="'+resp[r]+'"&gt;';
str += tmpr[r]+'&lt;/option&gt;';
} str += '&lt;/select&gt;'; break;
*/
default : str += q+': Invalid type: '+QR[q][0]; break;
}
str += "&lt;p /&gt;";
}
document.write(str);
&lt;/script&gt; <br/>
&lt;br /&gt;
&lt;br /&gt;

&lt;input type=button onClick="Score()" value="How awesome am I?"&gt;
&lt;/div&gt;
&lt;/ol&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;


Quiz.js
<i>
</i>// Quiz.js

var QR = [
['Question type','Question','Responses,...','Answers,...'], // format of QR array
['RB', "What was the start and end year of World War I?",
"1905 - 1910|1915 - 1920|1914 - 1918|None of the above","c"],
['CB', "What color is the sky? (Choose the three that best fit)",
"Blue|Red|Grey|White|Orange|Plaid","a|c|d"],
['SB', "Choose the world's fastest bird:",
"Select|Roadrunner|Peregrine falcon|Emu|Bald eagle","c"],
['SB', "What did Spartan warriors have to eat:",
"Select|Twinkies|Potato chips|Plain black broth|Fruit roll up","d"],
['CB', "What are common traits of mammals? (Choose all that apply)",
"Feathers|Warm blood|Prehensile tail|Green eyes|Hair|Lays eggs","b|e"] // No comma after last entry
];

var explainAnswer = [
"", // unused entry
"World War I started in 1914 and ended in 1918.",
"The sky can have any varying shades of blue, white or grey.",
"The Peregrine falcon is the world's speediest bird.",
"Plain black broth kept the Spartan warriors strong and fit. &lt;br&gt;Others are modern day inventions.",
"Mammals have warm blood and hair on their bodies." // No comma after last entry
];
Copy linkTweet thisAlerts:
@neptunegirlauthorApr 18.2009 — You are amazing! How will I ever be a coder like you...


?
Copy linkTweet thisAlerts:
@dmboydApr 18.2009 — You are amazing! How will I ever be a coder like you...


?[/quote]

Hopefully you won't be. You'll develop your own sense of style and what you consider to be "best coding practices". Sometimes people will tell you that they're actually bad coding practices, which they may be. However, there are some that aren't bad at all; they're just conceived and used before the rest of the world is ready for them. In addition, not all "best practices" work for all languages. Example --
[LIST]
  • [*]HTML, XHTML, XML, etc.
    [LIST]
  • [*]Number of spaces per indentation level: 2

  • [*]Quotation marks used most often: double quotation marks

  • [/LIST]


  • [*]C and C++
    [LIST]
  • [*]Number of spaces per indentation level: 2

  • [*]Opening brace location: on its own line

  • [*]Closing brace location: on its own line

  • [*]Location of the function name for function declarations: same line as the function return type

  • [*]Location of the function name for function definitions: on a line with its arguments, the preceding line consisting solely of the function return type

  • [*]Quotation marks used most often: double quotation marks

  • [/LIST]

  • [*]Java, JavaScript and C#
    [LIST]
  • [*]Number of spaces per indentation level: 4

  • [*]Opening brace location: on the same line as the text before it unless it is used solely to create a new scope, in which case it is used as in C/C++

  • [*]Closing brace location: on its own line

  • [*]Quotation marks used most often: double quotation marks

  • [/LIST]

  • [*]Python
    [LIST]
  • [*]Number of spaces per indentation level: 4

  • [*]Assignment statements: always spaced out except in the case of default argument assignments, where my default arguments have no space between the argument, the '=' character and the default value

  • [*]Quotation marks used most often: single quotation marks

  • [/LIST]

  • [*]PHP
    [LIST]
  • [*]Number of spaces per indentation level: 4

  • [*]Opening brace location: on the same line as the text before it, just as in Java, JavaScript and C#

  • [*]Closing brace location: on its own line

  • [*]Quotation marks used most often: single quotation marks (when possible).

  • [/LIST]

    [/LIST]
    Crazy list, right? Believe it or not, I adhere to every one of them. My editor (GNU Emacs) auto-indents things for me, but I do everything else pretty much (except in the case of text strings and comments, where such items wrap to 70/76 columns automatically depending upon my preference at the time).
    Copy linkTweet thisAlerts:
    @JMRKERApr 19.2009 — Hopefully you won't be. You'll develop your own sense of style and what you consider to be "best coding practices". Sometimes people will tell you that they're actually bad coding practices, which they may be. However, there are some that aren't bad at all; they're just conceived and used before the rest of the world is ready for them. In addition, not all "best practices" work for all languages. Example --

    ...
    [/QUOTE]


    OK, I'll bite ... what does style have to do with function? ?

    If it functions correctly, you can rearrange the code anyway that that pleases you. If I manage to save some space in the process, it should load faster.

    The only time I like the code in a specific format is 1) when I write it and 2) when I change (debug) it. Other than those times, I don't look at the format of the code. If I'm consistent with my style and I obey my rules, why is it better to follow your rules? :eek:

    Granted, you can make it look pretty and make the display uniform for screen and waste more paper with a printout, but how does that effect the execution of the script? ?

    Or perhaps I'm misunderstanding the intent of the comments in the post. :o
    Copy linkTweet thisAlerts:
    @dmboydApr 19.2009 — If I'm consistent with my style and I obey my rules, why is it better to follow your rules? :eek:[/quote]That's my point exactly.You are amazing! How will I ever be a coder like you...[/quote]Hopefully you won't be. You'll develop your own sense of style and what you consider to be "best coding practices".[/quote]Perhaps I switched onto a tangent and stuck with it... Writing is a strong suit of mine, but I seem to have a rather annoying problem with staying focused. :p
    Copy linkTweet thisAlerts:
    @JMRKERApr 19.2009 — OK ... no harm, no foul. ?
    ×

    Success!

    Help @neptunegirl spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.15,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...