JavaScript Need help How to validate my quiz answers till the end to show a full score?

huha2511

New Coder
Nov 1, 2019
9
3
3
Hi, I am new here!
I need help for my Quiz assignment as I have a problem in my Javascript.
My quiz has a textbox, radio and checkbox.
At first, the checkAnswer() worked when I did not input the show() function to my JavaScript. It showed my overall score.
But after I input that show() function to display 1 question at a time, my score is always 5/7 or less.
Please do tell what is wrong with my code and if you have any recommendations. Please do tell.
Here is the demo. Click here

Here is my javascript
JavaScript:
function show(param_div_id) {
    document.getElementById('start').innerHTML = document.getElementById(param_div_id).innerHTML;
  }
//FORCE UPPERCASE
  document.getElementById("field1").addEventListener("keypress", forceKeyPressUppercase, false);
  document.getElementById("field2").addEventListener("keypress", forceKeyPressUppercase, false);
function retake() {
    location.reload();
}
//VALIDATE ANSWERS AND SCORE
    function checkAnswers(){        
  var number = 0;
    var numCorrect = 0;
    var totalQuestions = 3
      var q1 = document.forms['quizForm']['q1'].value.toString();
      var q2 = document.forms['quizForm']['q2'].value.toString();
      var q3 = document.forms['quizForm']['q3'].value.toString();
      var numCorrect=0;
    if(q1=="correct"){
        numCorrect++;
    }
    if((q2=="5") || (q2=="FIVE")){
        numCorrect++;
    }
    var checkboxes = document.getElementsByName("q3");
    var checkboxChecked = [];
    for(var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked && (checkboxes[i].value === "correct")) {
            checkboxChecked.push(checkboxes[i]);
        numCorrect++;
    }
    }
    alert("You got " +numCorrect+ " out of 7 correct");
}

Here is my HTML
HTML:
    <body>
        <div id="container" >  
            <div id="start"  >        
                <div id="ready">
                <button onclick="show('q1')"><h1>START NOW</h1></button>  
                </div>
            </div>
            <div id="quiz">        
            <form name="quizForm" >    
                <div id="q1"  style="display:none;" >
                <!--QUESTION 1-->
                     <div class="question">
                        <h1 >WHO WAS HE?</h1>  
                        <div>
                        <ul>
                        <li><input type="radio" name="q1" value="wrong"/>Ted</li>      
                        <li><input type="radio" name="q1" value="correct"/>Jack</li>  
                        <li><input type="radio" name="q1" value="wrong"/>John</li>                
                        </ul>
                        </div>
                    </div>
                    <button onclick="show('q2')"><h1>NEXT</h1></button>
                </div>
                <div id="q2" style="display:none;">
                <!--QUESTION 2-->
                <h1>TYPE HOW MANY VICTIMS</h1>
                    <div>
                    <input  onkeyup=" var start = this.selectionStart;var end = this.selectionEnd;this.value = this.value.toUpperCase(); this.setSelectionRange(start, end);" id="q2" type="text" name="q2" />                
                    </div>
                <button onclick="show('q3')"><h1>NEXT</h1></button>                
                </div>
                <div id="q3" style="display:none;">
                <!--QUESTION 3-->
                <h1>WHICH MOVIES WERE AN ADAPTATION?<br>pick more than 1</h1>
                    <div>
                    <ul>
                    <li><input type="checkbox" name="q3" value="correct"/>Psycho (1960)</li>
                    <li><input type="checkbox" name="q3" value="wrong"/>Kickass (2010)</li>
                    <li><input type="checkbox" name="q3" value="correct"/>American Psycho (2000)</li>
                    <li><input type="checkbox" name="q3" value="correct"/>Zodiac (2007)</li>
                    <li><input type="checkbox" name="q3" value="wrong"/>Perfume: The Story of a Murderer (2006)</li>
                    <li><input type="checkbox" name="q3" value="correct"/>Halloween (1978)</li>
                    <li><input type="checkbox" name="q3" value="correct"/>The Texas Chainsaw Massacre (1974)</li>
                    </ul>          
                    </div>
                <button type="submit" onclick="checkAnswers()"><h1>FINISHED</h1></button>
                </div>
            </form>        
            </div>        
        </div>        
    </body>
 
Last edited:

William

Active Coder
Sep 7, 2019
178
32
38
Okay, I'm back, fully rested and I'm ready to maybe take a further look at this.
I think it's because of the checkbox (question 3), it only checks that question as of now since the score for it is 5. The answer for Question 1 and 2 is still ignored by the JavaScript.
Right, okay. I think it's best if you do include the other Checkboxes as to avoid testers of the Code from being confused and yourself included, plus, the person who gave you the Assignment. The last thing you want is for people(Including the Project-Assigner) to be confused as to why the other Answers are not being registered to the Score.

I have tried it, there is still no changes TT-TT.
I take it that you're referring to the Variable that I referenced(var totalQuestions = 3 in this case). I think the reason why nothing is happening is because you haven't added the HTML for more Questions(Unless there are only meant to be 3 Questions. But again, this goes back to what I was saying about how I was confused as to why you were getting 5 out of 7). If there are meant to be more Questions then add the HTML for them. Then let the JS do it's work and have it progress the User onto the next Question. But again, as I stated earlier, you need to reference the other Checkboxes in: var checkboxes or else nothing is going to work and the Answers are not going to be registered to the Score.

Is there a reason used and not PHP?
There are now many users who block JavaSkript by default so a whole query is obsolete
@Tealk
It's because my assignment is based on JavaScript, CSS and HTML :cry:. But I think the jQuery use should be acceptable. But JavaScript should be present. :cry: And I haven't touch on PHP in my class.
I myself, block JS unless it's needed for a Site to function properly. But seeing as this is for an Assignment, I think we should just let the: "Why use JavaScript and not [Programming-Language]?" thing slide for now. As @huha2511 has stated, his Teacher has not covered PHP yet. And besides, PHP is just as much of a Security-Risk as JavaScript. PHP is also hated a lot and apparently, due to the rise of node.JS, Electron, Ruby/RoR and Python/Django/Flask, PHP is slowly becoming obsolete(Except in Forum-Softwares, Facebook still uses the damn thing and Legacy-Sites who still rely on it). While PHP is still useful, I would prefer to not learn it. Besides, I just looked at PHP Examples on Wikipedia, through Images and the PHP-Code for the SimpleMachines Forum Software and I have never seen Code that hideous in my life so far. A lot of other people also hate PHP. Just Ask-Reddit and you'll learn why.
 
  • Like
Reactions: huha2511

William

Active Coder
Sep 7, 2019
178
32
38
I don't have any experience with JavaScript but it has some similarities with Syntax regarding C and Lua so maybe I could help you with the JS Code.

But, I do have a good amount of experience with HTML so maybe I can identify any Issues with the HTML.

From what I've tested so far, there are only three Questions and thus' it stops after that. So I don't understand how you're getting five or less. But looking at the JS Code, the Variable: var totalQuestions = 3;, it essentially means that there are three Questions in total. Again, I'm not sure how you're getting more than three for your end-results. Perhaps there's something in the Code that's causing it.

As for the HTML, I don't see anything wrong with it. Maybe I'm not observing hard enough yet. But, as of Posting, I'm currently a bit tired after a long day and so I need to rest. I'll write another Post later with further observations to the Code.

As @Malcolm mentioned, @Ghost should be able to help you with this. He's an experienced with Web-Developer and he should be able to give you the results you want. @joe could potentially help you too.

Again, I'll Post later when I'm feeling refreshed and awake.
 
  • Like
Reactions: huha2511

huha2511

New Coder
Nov 1, 2019
9
3
3
I don't have any experience with JavaScript but it has some similarities with Syntax regarding C and Lua so maybe I could help you with the JS Code.

But, I do have a good amount of experience with HTML so maybe I can identify any Issues with the HTML.

From what I've tested so far, there are only three Questions and thus' it stops after that. So I don't understand how you're getting five or less. But looking at the JS Code, the Variable: var totalQuestions = 3;, it essentially means that there are three Questions in total. Again, I'm not sure how you're getting more than three for your end-results. Perhaps there's something in the Code that's causing it.

As for the HTML, I don't see anything wrong with it. Maybe I'm not observing hard enough yet. But, as of Posting, I'm currently a bit tired after a long day and so I need to rest. I'll write another Post later with further observations to the Code.

As @Malcolm mentioned, @Ghost should be able to help you with this. He's an experienced with Web-Developer and he should be able to give you the results you want. @joe could potentially help you too.

Again, I'll Post later when I'm feeling refreshed and awake.
I think it's because of the checkbox (question 3), it only checks that question as of now since the score for it is 5. The answer for Question 1 and 2 is still ignored by the JavaScript.
But I'll try to change and check as what you have pointed out. // I have tried it, there is still no changes TT-TT.
That's understandable @Crow. Do take a rest first.
And thank you for trying to help >.<
 
Last edited:
  • Like
Reactions: Malcolm

huha2511

New Coder
Nov 1, 2019
9
3
3
@Tealk
It's because my assignment is based on JavaScript, CSS and HTML :cry:. But I think the jQuery use should be acceptable. But JavaScript should be present. :cry: And I haven't touch on PHP in my class.
However, I am thinking to change all my questions to input: radio though because if I include all types, it is hard for me to code.:eek:
 

huha2511

New Coder
Nov 1, 2019
9
3
3
Please do recommend me a javascript/ jquery function that shows questions one at a time. Other than that show() function:thinking:
 

huha2511

New Coder
Nov 1, 2019
9
3
3
@Crow Yes, I agree. I just look up on PHP and it was like a whole new world :Rofl:
Oh yes, I have figured out how to finish the assignment. I implemented @Crow 's advice
and also tried using the show() function to just replace with the whole quiz form ( #quiz) after clicking the start button. And not each of the question.
Then the score showed 3/3. I'll just use that for now :laugh:Everyone, thank you for helping especially @Crow.:notworthy:
 
  • Like
Reactions: William

William

Active Coder
Sep 7, 2019
178
32
38
@Crow Yes, I agree. I just look up on PHP and it was like a whole new world
Believe me, if Web-Programming is what you want to pursue then choose the Languages carefully. PHP as I said, is just like JavaScript. It has a lot of Vulnerabilities with it but PHP is worse than JS in terms of Security. As I also said, Developers seem to hate it and when I say: 'hate it', I mean, they hate it. PHP Jobs also seem to be decreasing and according to the TIOBE Index, PHP is ranked #9 as of October 2019. And it's Change Column in the TIOBE marks it as Decreasing.

If you're going to purse Web-Programming, maybe go with the more popular choices such as Ruby/Ruby On Rails or Python and either the Django or Flask Frameworks. Besides, Python is an extremely popular Language(It's marked #3 in TIOBE) right now and Ruby(It's marked #13 in TIOBE) seems to be increasing in popularity.

Oh yes, I have figured out how to finish the assignment. I implemented @Crow 's advice
and also tried using the show() function to just replace with the whole quiz form ( #quiz) after clicking the start button. And not each of the question.
I'm glad that you have taken my advice into improving it. Is there a way to see your new changes? I'd also be interested in seeing the changes in the Code.

Everyone, thank you for helping especially @Crow.
I'm happy to have helped you with this. I wish you the best of luck with the Assignment-Results.
 
  • Like
Reactions: huha2511

huha2511

New Coder
Nov 1, 2019
9
3
3
@Crow Wow, I never heard of those names before. Will try to research more on this in the future:thinking: I just taken the module from my uni on web application this semester and that is why I am a noob at this haha
ah, and thank you again!!!
Most of the changes are in the HTML though haha :laugh:
Here is the demo with CSS LINK, but I don't know why after showing the scores, it goes to "bad path" at the codepen.
When I open it directly from my app, it also works and after it shows the score, it will go back to the front page ;).
The HTML for my quiz:
<body>

      <div id="container">
        <br><br>
        <div id="start">
          <div id="ready">
            <div id="startready">
              <H1>ARE YOU READY?</H1>
              <button class="start" onclick="show('quiz')">
                <h1>START NOW</h1>
              </button>
            </div>
          </div>
        </div>

        <div id="quiz" style="display:none;">
          <form name="quizForm">

            <div id="q1" class="question">
              <!--QUESTION 1-->
              <h3> The killer was never captured, and remains one of England's,
                and the world's, most infamous criminals.
                <br>In the 1800s, he killed women, removed their sexual
                and internal organs with surgical precision</h3>
              <p>Many movies were based on him</p>
              <img src="img/jack1.jpg" alt="The Ripper">
              <div class="question">
                <h1>WHO WAS HE?</h1>
                <div class="radio-toolbar">
                  <ul>
                    <li><input type="radio" id='q1-1' name="q1" value="wrong"><label for='q1-1'>Ted Bundy </label></li>
                    <li><input type="radio" id='q1-2' name="q1" class="correct" value="correct"><label for='q1-2'>Jack the Ripper</label></li>
                    <li><input type="radio" id='q1-3' name="q1" value="wrong"><label for='q1-3'>John Wayne Gacy</label></li>
                  </ul>
                </div>
              </div>
            </div>
            <div id="q2" class="question">
              <!--QUESTION 2-->
              <h3> Jack the Ripper had targeted mainly female prostitutes</h3>
              <img src="img/jack2.jpg" alt="The Clown">
              <h1>TYPE HOW MANY VICTIMS WERE THERE AT LEAST</h1>
              <br>
              <div class="textbox">
                <input onkeyup=" var start = this.selectionStart;var end = this.selectionEnd;this.value = this.value.toUpperCase(); this.setSelectionRange(start, end);" type="text" name="q2" />
              </div>
            </div>
            <div id="q3" class="question">
              <!--QUESTION 3-->
              <h3> There are various films that were based on true serial crimes</h3>
              <p> While some were from the epitome of imagination</p>
              <img src="img/TV.jpg" alt="Movies">
              <h1>WHICH MOVIE WAS ADAPTED FROM REAL LIFE KILLERS?</h1>
              <div class="radio-toolbar">
                <ul>
                  <li><input name='Q3' id='q3-1' type='radio'><label for='q3-1'>Perfume: The Story of a Murderer (2006)</label></li>
                  <li><input name='Q3' id='q3-2' type='radio' value="correct"><label for='q3-2'>Halloween (1978)</label></li>
                  <li><input name='Q3' id='q3-3' type='radio'><label for='q3-3'>Both</label></li>
                </ul>
              </div>
              <button type="submit" onclick="checkAnswers()">FINISHED</button>
            </div>
          </form>
        </div>
      </div>
    </body>
The JavaScript is still the same tho, only the last question's code is changed.
JavaScript:
function show(param_div_id) {
  document.getElementById('start').innerHTML = document.getElementById(param_div_id).innerHTML;
}

//FORCE UPPERCASE
document.getElementById("field1").addEventListener("keypress", forceKeyPressUppercase, false);
document.getElementById("field2").addEventListener("keypress", forceKeyPressUppercase, false);


//VALIDATE ANSWERS AND SCORE
function checkAnswers() {
  //Get user input for each question

  var number = 0;
  var numCorrect = 0;
  var totalQuestions = 3;

  var q1 = document.forms['quizForm']['q1'].value.toString();
  var q2 = document.forms['quizForm']['q2'].value.toString();
  var q3 = document.forms['quizForm']['q3'].value.toString();
  var numCorrect = 0;

  if (q1 == "correct") {
    numCorrect++;
  }
  if ((q2 == "5") || (q2 == "FIVE")) {
    numCorrect++;
  }
  if (q3 == "correct") {
    numCorrect++;
  }
  alert("You got " +numCorrect+ " out of 3 correct");
}
 
Last edited:

joe

Coder
Aug 21, 2019
32
15
8
Hey @huha2511 ,

I had a glance at the code and I think the problem is with the way you show/hide questions.

The show() function lifts the HTML from a hidden div 'quizForm' and displays it correctly in 'start' div; but when your checkAnswers() function tries to access the selected answers, it looks for them in those hidden divs and not in the 'start' div where they were actually displayed and changed by the user! Thats why their values are never being added to your 'numCorrect' count.

Find a way to retrieve the selected answer from inside the 'start' div and the code should work fine, I guess.

Hope it helps :)
 
  • Like
Reactions: huha2511

huha2511

New Coder
Nov 1, 2019
9
3
3
@joe Yes, I tried to add codes to the show() function to add the scores but I gave up on it o_O
So I just find another way to use the show() function cause the main thing that I want is to just separate the "start quiz' and the questions.
As I said before, I am still a noob in this hahaha:laugh: and I may have somewhat found my solution to finish my assignment as soon as possible ;)

But thank you for pointing out the error :) I will look into it after all my other school assignments are finished:cry:
 
Last edited:

Malcolm

Administrator
Administrator
Jan 2, 2018
1,065
295
95
Canada
codeforum.org
@joe Yes, I tried to add codes to the show() function to add the scores but I gave up on it o_O
So I just find another way to use the show() function cause the main thing that I want is to just separate the "start quiz' and the questions.
As I said before, I am still a noob in this hahaha:laugh: and I may have somewhat found my solution to finish my assignment as soon as possible ;)

But thank you for pointing out the error :) I will look into it after all my other school assignments are finished:cry:
Hey, I'm glad to see that you're starting to find some solutions, I'm just curious if you found the one! And perhaps you could share it? :)