简体   繁体   中英

JavaScript multiple choice quiz

i am creating a multiple choice quiz.For some reason it is not running.I have run it through the javascript console and it keeps telling me that submitAnswer is not a function. Here is the javascript code:

var userAnswers = [];
var answered = 0; 
var questions = [question1, question2, question3, question4, question5, question6, question7, question8, question9, question10];
var answers = [q1a, q1b, q1c, q1d, q2a, q2b, q2c, q2d, q3a, q3b, q3c, q3d, q4a, q4b, q4c, q4d, q5a, q5b, q5c, q5d, q6a, q6b, q6c, q6d, q7a, q7b, q7c, q7d];
function resetQuiz(showConfirm) {
  if(showConfirm)
    if(!confirm("Are you sure you want to reset the quiz and start from the beginning?"))
      return false;
  document.location = document.location;
}

var submitAnswer = function(questionId, obj, classId, labelId) {
  userAnswers[questionId] = answers.value;
  document.getElementById(labelId).style.fontWeight = "bold";
  disableQuestion(classId);
  showResult(questionId);
  answered++;
};

var submitAnswer = function() {
   var answer = document.getElementById(submitq1);
   userAnswers.push[answer];
};
  console.log(userAnswers); 

function showScore() {
  if(answered != answered.length) {
    alert("You have not answered all of the questions yet!");
    return false;
  }
 var questionCount = answered.length;
  var correct = 0;
 var incorrect = 0;
  for(var i=0;i<questionCount;i++) {
    if(userAnswers[i] == answered[i])
      correct++;
    else
      incorrect++;
  }
  var response = ["10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"];
   var pc = Math.round((correct / questionCount) * 100);
  var alertMsg = "You scored " + correct + " out of " + "10" + "\n\n";
  if(pc == 100)
    alertMsg += response[0];
  else if(pc >= 90)
    alertMsg += response[1];
  else if(pc>= 80)
    alertMsg += response[2];
  else if(pc >= 70)
    alertMsg += response[3];
  else if(pc > 60)
    alertMsg += response[4];
  else if(pc >= 50)
    alertMsg += response[5];
  else if(pc >= 40)
    alertMsg += response[6];
  else if(pc >= 30)
    alertMsg += response[7];
  else if(pc>= 20)
    alertMsg += response[8];
  else if(pc >= 10)
    alertMsg += response[9];
  else if(pc >= 0)
    alertMsg += response[10];
  if(pc < 100) {
    if(confirm(alertMsg))
      resetQuiz(false);
    else
      return false;
  } else {
    alert(alertMsg);
  }
}
function disableQuestion(classId) {
  var alltags=document.all? document.all : document.getElementsByTagName("*");
  for (var i=0; i<alltags.length; i++) {

    if (alltags[i].className == classId) {
      alltags[i].disabled = true;
    }
  }
};

html code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>

</head>
<body style="background-color: lightblue;">
<h1>Driving Test</h1>
<p class="questions">1. At what minimum distance away from a railroad should you stop?</p>

<img src="q1.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question1">
<input type="radio" name="q1" value="a" id="q1a">a. 6 meters from the nearest rail</label><br/>
<input type="radio" name="q1" value="b" id="q1b">b. 5 meters from the nearest rail</label><br/>
<input type="radio" name="q1" value="c" id="q1c">c. 10 meters from the nearest rail</label><br/>
<input type="radio" name="q1" value="d" id="q1d">d. 3 meters from the nearest rail</label><br/>
</ul>

<input type="button" value="submit" id="submitq1" onclick="submitAnswer();">

<p class="questions">2. When should you slow down to 30km/h near a playground?</p>

<img src="q2.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question2">
<input type="radio" name="q2" value="a" id="q2a">a. as soon as you notice that you are near a playground</label><br/>
<input type="radio" name="q2" value="b" id="q2b">b. when you see the playground sign</label><br/>
<input type="radio" name="q2" value="c" id="q2c">c. when you see the playground sign with a 30km/h limit</label><br/>
<input type="radio" name="q2" value="d" id="q2d">d. from dusk to dawn when you see the playground sign with a 30km/h limit</label><br/>
</ul>

<input type="button" value="submit" id="submitq2" onclick="submitAnswer();">

<p class="questions">3. A light with a steady red cross above a lane of traffic means:</p>

<img src="q3.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question3">
<input type="radio" name="q3" value="a" id="q3a">a. proceed with caution</label><br/>
<input type="radio" name="q3" value="b" id="q3b">b. begin moving out of this lane and into one with a green arrow</label><br/>
<input type="radio" name="q3" value="c" id="q3c">c. you cannot drive in this lane</label><br/>
<input type="radio" name="q3" value="d" id="q3d">Answer 4</label><br/>
</ul>

<input type="button" value="submit" id="submitq3" onclick="submitAnswer();">

<p class="questions">4. When entering a freeway you should always:</p>

<img src="q4.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question4">
<input type="radio" name="q4" value="a" id="q4a">a. slow down and proceed when it is safe</label><br/>
<input type="radio" name="q4" value="b" id="q4b">b. stop and make sure this is no traffic approaching</label><br/>
<input type="radio" name="q4" value="c" id="q4c">c. signal, accelerate to the same speed as the freeway traffic and merge smoothly</label><br/>
<input type="radio" name="q4" value="d" id="q4d">d. go as fast as you can and swing into traffic</label><br/>
</ul>

<input type="button" value="submit" id="submitq4" onclick="submitAnswer();">

<p class="questions">5. What is the minimum following distance you should leave between your vehicle and a motorcycle in front of you?</p>

<img src="q5.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question5">
<input type="radio" name="q5" value="a" id="q5a">a. 2 seconds</label><br/>
<input type="radio" name="q5" value="b" id="q5b">b. 3 seconds</label><br/>
<input type="radio" name="q5" value="c" id="q5c">c. 4 seconds</label><br/>
<input type="radio" name="q5" value="d" id="q5d">d. 5 seconds</label><br/>
</ul>

<input type="button" value="submit" id="submitq5" onclick="submitAnswer();">

<p class="questions">6. To help prevent collision with an animal you should:</p>

<img src="q6.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question6">
<input type="radio" name="q6" value="a" id="q5a">a. scan the sides of the road ahead for animals</label><br/>
<input type="radio" name="q6" value="b" id="q5b">b. watch for animal crossing signs</label><br/>
<input type="radio" name="q6" value="c" id="q5c">c. be extra cautious at dusk and dawn</label><br/>
<input type="radio" name="q6" value="d" id="q6d">d. all of the above</label><br/>
</ul>

<input type="button" value="submit" id="submitq6" onclick="submitAnswer();">

<p class="questions">7. If your tire blows while driving you should:</p>

<img src="q7.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question7">
<input type="radio" name="q7" value="a" id="q7a">a. slam on the brakes, hold the wheel firmly and pull over</label><br/>
<input type="radio" name="q7" value="b" id="q7b">b. drive as fast as you can to the nearest service station</label><br/>
<input type="radio" name="q7" value="c" id="q7c">c. ease off the gas pedal, hold the wheel firmly, signal and pull over</label><br/>
<input type="radio" name="q7" value="d" id="q7d">d. stop right away to avoid ruining your tires even more</label><br/>
</ul>

<input type="button" value="submit" id="submitq7" onclick="submitAnswer();">

<p class="questions">8. If you are in an accident you must:</p>

<img src="q8.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question8">
<input type="radio" name="q8" value="a" id="q8a">a. stop to give assitance and give your number and insurance info to others involved</label><br/>
<input type="radio" name="q8" value="b" id="q8b">b. stop only if the accident is serious</label><br/>
<input type="radio" name="q8" value="c" id="q8c">c. stop only to check whether damage has occured</label><br/>
<input type="radio" name="q8" value="d" id="q8d">d. only if someone is injured</label><br/>
</ul>

<input type="button" value="submit" id="submitq8" onclick="submitAnswer();">

<p class="questions">9. This sign means:</p>

<img src="q9.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="questions" id="question9">
<input type="radio" name="q9" value="a" id="q9a">a. use your headlights</label><br/>
<input type="radio" name="q9" value="b" id="q9b">b. winding road ahead</label><br/>
<input type="radio" name="q9" value="c" id="q9c">c. road may be slippery ahead</label><br/>
<input type="radio" name="q9" value="d" id="q9d">d. curve ahead</label><br/>
</ul>

<input type="button" value="submit" id="submitq9" onclick="submitAnswer();">

<p class="questions">10. When approaching a railway crossing you should always:</p>

<img src="q10.jpg" alt="Mountain View" style="width:304px;height:228px;">

<ul class="answers" id="question10">
<input type="radio" name="q10" value="a" id="q10a">a. look for advance warning signs</label><br/>
<input type="radio" name="q10" value="b" id="q10b">b. watch out for all other road users</label><br/>
<input type="radio" name="q10" value="c" id="q10c">c. observe carefully as train often appear to move more slowly than they are</label><br/>
<input type="radio" name="q10" value="d" id="q10d">d. all of the above</label><br/>
</ul>

<input type="button" value="submit" id="submitq10" onclick="submitAnswer();">


<div id="question1">            
<p>              
<strong>Question 1:</strong> The correct answer is the <strong>Answer 2</strong>.</p>        
</div>        

<div id="question2">            
<p>              
<strong>Question 2:</strong> The correct answer is <strong>Answer 4</strong>.</p>        
</div>        

<div id="question3">            
<p>                
<strong>Question 3:</strong> The correct answer is <strong>Answer 3</strong>.</p>        
</div>        

<div id="question4">            
<p>               
<strong>Question 4:</strong> The correct answer is <strong>Answer 3</strong>.</p>        
</div>        

<div id="question5">            
<p>                
<strong>Question 5:</strong> The correct answer is <strong>Answer 2</strong>.</p>        
</div>        

<div id="question6">            
<p>                
<strong>Question 6:</strong> The correct answer is <strong>Answer 4</strong>.</p>        
</div>        

<div id="question7">            
<p>                
<strong>Question 7:</strong> The correct answer is <strong>Answer 3</strong>.</p>        
</div>        

<div id="question8">            
<p>               
<strong>Question 8:</strong> The correct answer is <strong>Answer 1</strong>.</p>        
</div>        

<div id="question9">           
<p>               
<strong>Question 9:</strong> The correct answer is <strong>Answer 3</strong>.</p>        
</div>        

<div id="question10">            
<p>                
<strong>Question 10:</strong> The correct answer is <strong>Answer 4</strong>.</p>        
</div>        

<div id="category11">            
<p>                
All answers are correct</p>        
</div>
<script src="groupproject.js"></script>

</body>
</html>

The reason it's saying submitAnswer is not a function is because you have defined it as a variable so JS won't hoist it properly. Rather than using

var submitAnswer= function(blah){blah}

just use

function submitAnswer(blah){blah}

Also, make sure you seem to have declared submitAnswer twice. Make sure you use the right one.

I'm not sure why it says submitAnswer is not a function, but you have defined two functions with that same name which is not allowed in JS. Try renaming one of them or change the parameter list as suggested here and then post more information if the problem continues.

Functions in Javascript are generally defined in the following manner:

function submitAnswer(){
    //code here
}

And then can be called after they are declared. If you have more than one function with the same name, you can overload it by providing a different parameter list for each one.

There are several things to address here, I will try to point out the most severe issues:

First, you have duplicate declaration of the function submitAnswer:

var submitAnswer = function(questionId, obj, classId, labelId) {
  userAnswers[questionId] = answers.value;
  document.getElementById(labelId).style.fontWeight = "bold";
  disableQuestion(classId);
  showResult(questionId);
  answered++;
};

var submitAnswer = function() {
   var answer = document.getElementById(submitq1);
   userAnswers.push[answer];
};

I guess you only want one of them, when writing it like this the second one will overwrite the first one. I'm guessing it is the first one you want to keep as it seems the most complete.

Second, your question 6 has the wrong IDs

<ul class="answers" id="question6">
  <input type="radio" name="q6" value="a" id="q5a">a. scan the sides of the road ahead for animals</label><br/>
  <input type="radio" name="q6" value="b" id="q5b">b. watch for animal crossing signs</label><br/>
  <input type="radio" name="q6" value="c" id="q5c">c. be extra cautious at dusk and dawn</label><br/>
  <input type="radio" name="q6" value="d" id="q6d">d. all of the above</label><br/>
</ul>

If you are looping through this array to match it with id you will not get the correct element, change id to 'q6[a|b|c|d]'.

When you have addressed this the next step would be to create your submitAnswer function, it is a bit unclear how you want it to work from your example.

A good first step would be to separate your view/html structure from your logic/JavaScript and read up on how parameters are passed to functions, I have cleaned your code up a bit to give you a stepping stone in this snippet:

 var userAnswers = []; var answered = 0; var questions = [question1, question2, question3, question4, question5, question6, question7, question8, question9, question10]; var answers = [q1a, q1b, q1c, q1d, q2a, q2b, q2c, q2d, q3a, q3b, q3c, q3d, q4a, q4b, q4c, q4d, q5a, q5b, q5c, q5d, q6a, q6b, q6c, q6d, q7a, q7b, q7c, q7d]; function resetQuiz(showConfirm) { if (showConfirm) if (!confirm("Are you sure you want to reset the quiz and start from the beginning?")) return false; document.location = document.location; } var submitAnswer = function() { console.log("submitted answer!"); }; function showScore() { if (answered != answered.length) { alert("You have not answered all of the questions yet!"); return false; } var questionCount = answered.length; var correct = 0; var incorrect = 0; for (var i = 0; i < questionCount; i++) { if (userAnswers[i] == answered[i]) correct++; else incorrect++; } var response = ["10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"]; var pc = Math.round((correct / questionCount) * 100); var alertMsg = "You scored " + correct + " out of " + "10" + "\\n\\n"; if (pc == 100) alertMsg += response[0]; else if (pc >= 90) alertMsg += response[1]; else if (pc >= 80) alertMsg += response[2]; else if (pc >= 70) alertMsg += response[3]; else if (pc > 60) alertMsg += response[4]; else if (pc >= 50) alertMsg += response[5]; else if (pc >= 40) alertMsg += response[6]; else if (pc >= 30) alertMsg += response[7]; else if (pc >= 20) alertMsg += response[8]; else if (pc >= 10) alertMsg += response[9]; else if (pc >= 0) alertMsg += response[10]; if (pc < 100) { if (confirm(alertMsg)) resetQuiz(false); else return false; } else { alert(alertMsg); } } function disableQuestion(classId) { var alltags = document.all ? document.all : document.getElementsByTagName("*"); for (var i = 0; i < alltags.length; i++) { if (alltags[i].className == classId) { alltags[i].disabled = true; } } };
 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body style="background-color: lightblue;"> <h1>Driving Test</h1> <p class="questions">1. At what minimum distance away from a railroad should you stop?</p> <img src="q1.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question1"> <input type="radio" name="q1" value="a" id="q1a">a. 6 meters from the nearest rail</label> <br/> <input type="radio" name="q1" value="b" id="q1b">b. 5 meters from the nearest rail</label> <br/> <input type="radio" name="q1" value="c" id="q1c">c. 10 meters from the nearest rail</label> <br/> <input type="radio" name="q1" value="d" id="q1d">d. 3 meters from the nearest rail</label> <br/> </ul> <input type="button" value="submit" id="submitq1" onclick="submitAnswer();"> <p class="questions">2. When should you slow down to 30km/h near a playground?</p> <img src="q2.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question2"> <input type="radio" name="q2" value="a" id="q2a">a. as soon as you notice that you are near a playground</label> <br/> <input type="radio" name="q2" value="b" id="q2b">b. when you see the playground sign</label> <br/> <input type="radio" name="q2" value="c" id="q2c">c. when you see the playground sign with a 30km/h limit</label> <br/> <input type="radio" name="q2" value="d" id="q2d">d. from dusk to dawn when you see the playground sign with a 30km/h limit</label> <br/> </ul> <input type="button" value="submit" id="submitq2" onclick="submitAnswer();"> <p class="questions">3. A light with a steady red cross above a lane of traffic means:</p> <img src="q3.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question3"> <input type="radio" name="q3" value="a" id="q3a">a. proceed with caution</label> <br/> <input type="radio" name="q3" value="b" id="q3b">b. begin moving out of this lane and into one with a green arrow</label> <br/> <input type="radio" name="q3" value="c" id="q3c">c. you cannot drive in this lane</label> <br/> <input type="radio" name="q3" value="d" id="q3d">Answer 4</label> <br/> </ul> <input type="button" value="submit" id="submitq3" onclick="submitAnswer();"> <p class="questions">4. When entering a freeway you should always:</p> <img src="q4.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question4"> <input type="radio" name="q4" value="a" id="q4a">a. slow down and proceed when it is safe</label> <br/> <input type="radio" name="q4" value="b" id="q4b">b. stop and make sure this is no traffic approaching</label> <br/> <input type="radio" name="q4" value="c" id="q4c">c. signal, accelerate to the same speed as the freeway traffic and merge smoothly</label> <br/> <input type="radio" name="q4" value="d" id="q4d">d. go as fast as you can and swing into traffic</label> <br/> </ul> <input type="button" value="submit" id="submitq4" onclick="submitAnswer();"> <p class="questions">5. What is the minimum following distance you should leave between your vehicle and a motorcycle in front of you?</p> <img src="q5.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question5"> <input type="radio" name="q5" value="a" id="q5a">a. 2 seconds</label> <br/> <input type="radio" name="q5" value="b" id="q5b">b. 3 seconds</label> <br/> <input type="radio" name="q5" value="c" id="q5c">c. 4 seconds</label> <br/> <input type="radio" name="q5" value="d" id="q5d">d. 5 seconds</label> <br/> </ul> <input type="button" value="submit" id="submitq5" onclick="submitAnswer();"> <p class="questions">6. To help prevent collision with an animal you should:</p> <img src="q6.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question6"> <input type="radio" name="q6" value="a" id="q6a">a. scan the sides of the road ahead for animals</label> <br/> <input type="radio" name="q6" value="b" id="q6b">b. watch for animal crossing signs</label> <br/> <input type="radio" name="q6" value="c" id="q6c">c. be extra cautious at dusk and dawn</label> <br/> <input type="radio" name="q6" value="d" id="q6d">d. all of the above</label> <br/> </ul> <input type="button" value="submit" id="submitq6" onclick="submitAnswer();"> <p class="questions">7. If your tire blows while driving you should:</p> <img src="q7.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question7"> <input type="radio" name="q7" value="a" id="q7a">a. slam on the brakes, hold the wheel firmly and pull over</label> <br/> <input type="radio" name="q7" value="b" id="q7b">b. drive as fast as you can to the nearest service station</label> <br/> <input type="radio" name="q7" value="c" id="q7c">c. ease off the gas pedal, hold the wheel firmly, signal and pull over</label> <br/> <input type="radio" name="q7" value="d" id="q7d">d. stop right away to avoid ruining your tires even more</label> <br/> </ul> <input type="button" value="submit" id="submitq7" onclick="submitAnswer();"> <p class="questions">8. If you are in an accident you must:</p> <img src="q8.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question8"> <input type="radio" name="q8" value="a" id="q8a">a. stop to give assitance and give your number and insurance info to others involved</label> <br/> <input type="radio" name="q8" value="b" id="q8b">b. stop only if the accident is serious</label> <br/> <input type="radio" name="q8" value="c" id="q8c">c. stop only to check whether damage has occured</label> <br/> <input type="radio" name="q8" value="d" id="q8d">d. only if someone is injured</label> <br/> </ul> <input type="button" value="submit" id="submitq8" onclick="submitAnswer();"> <p class="questions">9. This sign means:</p> <img src="q9.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="questions" id="question9"> <input type="radio" name="q9" value="a" id="q9a">a. use your headlights</label> <br/> <input type="radio" name="q9" value="b" id="q9b">b. winding road ahead</label> <br/> <input type="radio" name="q9" value="c" id="q9c">c. road may be slippery ahead</label> <br/> <input type="radio" name="q9" value="d" id="q9d">d. curve ahead</label> <br/> </ul> <input type="button" value="submit" id="submitq9" onclick="submitAnswer();"> <p class="questions">10. When approaching a railway crossing you should always:</p> <img src="q10.jpg" alt="Mountain View" style="width:304px;height:228px;"> <ul class="answers" id="question10"> <input type="radio" name="q10" value="a" id="q10a">a. look for advance warning signs</label> <br/> <input type="radio" name="q10" value="b" id="q10b">b. watch out for all other road users</label> <br/> <input type="radio" name="q10" value="c" id="q10c">c. observe carefully as train often appear to move more slowly than they are</label> <br/> <input type="radio" name="q10" value="d" id="q10d">d. all of the above</label> <br/> </ul> <input type="button" value="submit" id="submitq10" onclick="submitAnswer();"> <div id="question1"> <p> <strong>Question 1:</strong> The correct answer is the <strong>Answer 2</strong>.</p> </div> <div id="question2"> <p> <strong>Question 2:</strong> The correct answer is <strong>Answer 4</strong>.</p> </div> <div id="question3"> <p> <strong>Question 3:</strong> The correct answer is <strong>Answer 3</strong>.</p> </div> <div id="question4"> <p> <strong>Question 4:</strong> The correct answer is <strong>Answer 3</strong>.</p> </div> <div id="question5"> <p> <strong>Question 5:</strong> The correct answer is <strong>Answer 2</strong>.</p> </div> <div id="question6"> <p> <strong>Question 6:</strong> The correct answer is <strong>Answer 4</strong>.</p> </div> <div id="question7"> <p> <strong>Question 7:</strong> The correct answer is <strong>Answer 3</strong>.</p> </div> <div id="question8"> <p> <strong>Question 8:</strong> The correct answer is <strong>Answer 1</strong>.</p> </div> <div id="question9"> <p> <strong>Question 9:</strong> The correct answer is <strong>Answer 3</strong>.</p> </div> <div id="question10"> <p> <strong>Question 10:</strong> The correct answer is <strong>Answer 4</strong>.</p> </div> <div id="category11"> <p> All answers are correct</p> </div> </body> </html>

If you are learning to program you should try to do the rest by yourself, however if you are only looking for a multiple choice for your site/a project I suggest looking into some of the existing quizes/multiple choices that already exists.

One such (disclosure: which I develop for) is the H5P plugin , which has a multiple choice content type. It is completely free and open source, you can have a look at the code on github .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM