Jump to content

Building a Quiz


Ananemain

Recommended Posts

Hey W3!

 

I'm working on building an online quiz. The form is built using HTML (and looks pretty good), but all of the processing needs to be done with JS. I'm incredibly new to the coding game and need some serious help with this. The collection of tutorials, code snippets, and articles I've read haven't helped much, so now I'm here.

 

Functionally, all the code needs to do is verify whether or not the person entered his/her name and if the answer to each question is correct. If correct, it adds one to the score. If not, it does nothing. I've included my existing, completely non-working code below as well as the HTML to give you a sense of what I'm working with.

 

I need some direction and some sound advice on where to take my code from here. And how to get the whole thing to run properly. It needs to display the results somewhere on the page (or on a different page, whichever is easier) when the "Submit" button is clicked. (Sadly, I can't use an alert to show the results.) Just as a disclaimer, I DON'T want you to write the code for me. Just some general code bits or a push in the right direction would be immensely helpful. I'm sort of at the end of my rope here.

 

Thanks!

 

Javascript

var totalquestions = 10var correctchoices = new Array[]correctchoices[0] ='c' correctchoices[1] ='b' correctchoices[2] ='d'correctchoices[3] ='c'correctchoices[4] ='d'correctchoices[5] ='d'correctchoices[6] ='a'correctchoices[7] ='d'correctchoices[8] ='a'correctchoices[9] ='a'function gradeit(){var incorrect=nullfor (q=1;q<=totalquestions;q++){	var thequestion=eval("document.myquiz.question"+q)	for (c=0;c<thequestion.length;c++){		if (thequestion[c].checked==true)		actualchoices[q]=thequestion[c].value		}			if (actualchoices[q]!=correctchoices[q]){		if (incorrect==null)		incorrect=q		else		incorrect+="/"+q		}	}if (incorrect==null)incorrect="a/b"document.cookie='q='+incorrectif (document.cookie=='')alert("Your browser does not accept cookies. Please adjust your browser settings.")elsewindow.location="results.htm"}function showsolution(){var win2=window.open("","win2","width=200,height=350, scrollbars")win2.focus()win2.document.open()win2.document.write('<title>Solution</title>')win2.document.write('<body bgcolor="#FFFFFF">')win2.document.write('<center><h3>Solution to Quiz</h3></center>')win2.document.write('<center><font face="Arial">')for (i=1;i<=totalquestions;i++){for (temp=0;temp<incorrect.length;temp++){if (i==incorrect[temp])wrong=1}if (wrong==1){win2.document.write("Question "+i+"="+correctchoices[i].fontcolor("red")+"<br>")wrong=0}elsewin2.document.write("Question "+i+"="+correctchoices[i]+"<br>")}win2.document.write('</center></font>')win2.document.write("<h5>Note: The solutions in red are the ones to the questions you had incorrectly answered.</h5><p align='center'><small><a href='http://www.javascriptkit.com' target='_new'>JavaScript Kit quiz script</a></small>")win2.document.close()}

HTML

<!DOCTYPE html><html><head>	<link rel="stylesheet" link href="Style.css" type="text/css"</>    <script src="quizscript.js"></script>    <script>        var actualchoices=new Array() document.cookie="ready=yes"    </script></head><body>    <div id="container" style="width:1000px">    <div id="header">        <h1 style="margin-bottom:0;">ePortfolio for Designing Integrated Media Environments 2</h1>        <h3>Sherry Walsh</h3>    </div>                <hr>        <div id="menu">               <b>Menu</b>              <ul class="a">                 <li><a href="index.html">Home Page</a></l1>                  <l1><a href="Assign1index.html">About Me</a></l1>                  <li><a href="Assign2index.html">Greyhounds</a></li>                  <li>Assignment 3</li>                  <li>Assignment 4</li>                  <li>Assignment 5</li>                  <li>Assignment 6</li>                  <li>Assignment 7</li>              </ul>          </div>        <div id="content">        <div id="text">             <br>                       <h2>Greyhounds</h2><br>              <b>Please type in your name:</b><input type="text" id= "name" name="name"><br>             <form method="POST" name="myquiz">             <p><B>Please fill in the blank with the best word choice, then answer the questions below.</B></p>           <a href="http://greyhounddogsite.com" target="_blank"><img src="greyhound-and-cat.jpg" style="float:right; width:400px; padding-top:15px;padding-left:15px;" alt="Greyhound resting with cat."></a>                             <p>Greyhound racing is the sixth most             <span id="GapSpan0" class="question1">                <select id="question1">                    <option value="a">Please Answer</option>                           <option value="b">expensive</option>                    <option value="c">popular</option>                    <option value="d">daring</option>                </select>            </span>                    spectator sport in the United States. Over the last decade, a growing number of racers have been adopted to spend their retirement as household pets, once their racing careers are over.            </p><br>            <p>Many people             <span id="GapSpan1" class="question2">                 <select id="question2">                    <option value="a">Please Answer</option>                           <option value="b">hesitate</option>                    <option value="c">are eager</option>                    <option value="d">wish</option>                </select>            </span>            to adopt a retired racing greyhound because they think only very old dogs are available. Actually, even champion racers only work until they are about three-and-a-half years old. Because greyhounds usually live to be 12 to 15 years old, their retirement is much longer than their racing careers.            </p><br>            <p>People worry that a greyhound will be more nervous and active than other breeds and will need a large space to run. These are false impressions. Greyhounds have naturally sweet, mild dispositions, and while they love to run, they are             <span id="GapSpan2" class="question3">                <select id="question3">                    <option value="a">Please Answer</option>                            <option value="b">milers</option>                    <option value="c">marathoners</option>                    <option value="d">sprinters</option>                </select>            </span>            rather than distance runners and are sufficiently exercised with a few daily laps around a fenced-in backyard.</p><br>            <p>Greyhounds do not make good watchdogs, but they are very good with children, get along well with other dogs (and usually cats as well), and are             <span id="GapSpan3" class="question4">                <select id="question4">                    <option value="a">Please Answer</option>                            <option value="b">agressive</option>                    <option value="c">affectionate</option>                    <option value="d">disloyal</option>                </select>            </span>           and loyal. They are intelligent, well-behaved dogs, usually housebroken in only a few days. A retired racing greyhound is a wonderful pet for almost anyone.            </p><br>             <p><b>Please select the best answer.</b></p>               <p id="Q1">Based on the tone of the passage, the author's main purpose is to:</p>            <input type="radio" name="question5" id="question5"                      value="a"/>teach prospective owners how to transform their racing greyhound into a good pet.<br>            <input type="radio" name="question5" id="question5"                       value="b">show how the greyhound's nature makes it equally good as racer and pet.<br>            <input type="radio" name="question5" id="question5"                           value="c">encourage people to adopt retired racing greyhounds.<br>            <input type="radio" name="question5" id="question5"                          value="d">objectively present the pros and cons of adopting a racing greyhound.<br><br>                        <p id="Q2">According to the passage, adopting a greyhound is a good idea for people who</p>                <input type="radio" name="question6"id="question6"                          value="a">do not have children.<br>                <input type="radio" name="question6"id="question6"                           value="b">live in apartments.<br>                <input type="radio" name="question6" id="question6"                              value="c">do not usually like dogs.<br>                <input type="radio" name="question6" id="question6"                          value="d">already have another dog or a cat.<br>                        <p id="Q3">Which of the following is implied by the passage?</p>                    <input type="radio" name="question7" id="question7"                     value="a">The public is more aware of greyhounds than they used to be.<br>            <input type="radio" name="question7" id="question7"                      value="b">Greyhounds are more competitive than other dogs.<br>            <input type="radio" name="question7" id="question7"                          value="c">Greyhound racing should not be allowed.<br>            <input type="radio" name="question7" id="question7"                         value="d">People who own pet rabbits should not adopt greyhounds.<br>                               <p id="Q4">One drawback of adopting a greyhound is that</p>              <input type="radio" name="question8" id="question8"                    value="a">greyhounds are not good with children.<br>            <input type="radio" name="question8" id="question8"                     value="b">greyhounds are old when they retire from racing.<br>            <input type="radio" name="question8" id="question8"                      value="c">the greyhound's sensitivity makes it temperamental.<br>            <input type="radio" name="question8" id="question8"                       value="d">greyhounds are not good watch dogs.<br>                       <p><b>Please check all of the correct answers.</b></p>            <p id="Q5">This passage is most like an advertisement because it</p>            <input type="checkbox" name="question9" id="question9" value="b">uses statistics to prove its point.<br>            <input type="checkbox" name="question9" id="question9" value="a">presents information to substantiate its claims.<br>            <input type="checkbox" name="question9" id="question9" value="b">says nothing negative about greyhounds.<br>            <input type="checkbox" name="question9" id="question9" value="a">encourages people to do something.<br>                             <p id="Q6">According to the passage, a retired racing greyhound available for adoption will most likely be</p>            <input type="checkbox" name="question10" id="question10" value="b">happy to be retiring.<br>            <input type="checkbox" name="question10" id="question10" value="a">easily housebroken.<br>            <input type="checkbox" name="question10" id="question10" value="b">less high-strung than those that are not available for adoption.<br>            <input type="checkbox" name="question10" id="question10" value="a">a wonderful pet for almost anyone.<br>  </p>     </form> <form><div align="center"><input type="button" value="Grade Me!" name="B1" onClick="gradeit()"> <input type="button" value="Reset" name="B2" onClick="document.myquiz.reset()">       </div></form>        <p>Name of first form:            <script>                document.write(document.forms[0].name);            </script></p>      <p>Passage and questions are from: <a href=http://www.education.com/study-help/article/passage-51/ target="_blank">education.com</a></p>        </div>        </div>        </div>       </div>    </body></html>
Link to comment
Share on other sites

Most important, there's a syntax error here:

var correctchoices = new Array[]

Those should be parentheses, or you can substitute "new Array" with an empty set of square backets:

// Eithervar correctchoices = new Array();// Orvar correctchoices = [];

Secondly, you need learn to write code properly.

Otherwise unexpected things can occur and people managing your code (including yourself) may not be sure what the code was really supposed to do.

 

To make sure unexpected behavior doesn't occur, it's proper in Javascript to end all your lines of code (except curly braces { } ) with a semi-colon ";"

 

Line breaks might not always be there or might not be interpretted as line breaks (Mac line breaks are r while UNIX line breaks are n, Windows expect rn), so the semi-colon is used to show the end of a line.

var totalquestions = 10;var correctchoices = [];correctchoices[0] ='c';correctchoices[1] ='b';correctchoices[2] ='d';// etc

To prevent confusion put curly braces on all your statements, if(), while(), for() and the rest.

For example, change this:

if (incorrect==null)incorrect=qelseincorrect+="/"+q

To this:

if (incorrect==null) {    incorrect=q} else {    incorrect+="/"+q}

If you don't do that, people might not be sure where your condition was really meant to end, or you might find yourself adding an extra line of code after the if() and then getting an error.

 

 

Solving your problem

Your code logic, glancing over it, seems OK. Is it working or not?

 

I wouldn't use document.write() because it will delete absolutely everything from the page and begin writing a new document, which is usually not the desired behavior. Learn HTML DOM to put things into your HTML document. Probably the most useful properties for you will be getElementById() and innerHTML.

 

Best practises

In order to make sure that Javascript is seeing the same document that you think you're seeing you have to make sure your document is valid HTML. Use the W3C validator. You can copy your code and paste it right there on the site using the "direct input" dialog. The validator says there are 30 errors.

 

Security

The fact that the answers are in your Javascript code means that cheating on your quiz is no more difficult than pressing Control+U in the browser and looking at the source code. These kinds of quizzes are always done using a server-side language because the user doesn't have access to server-side code.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...