Quiz with Vanilla JavaScript

Quiz with Vanilla JavaScript
0
#1

I’ve made a thread some days ago about a quiz with JS, but that thread took many comments and thought submitting a new thread would be easier to solve my problems.
Anyway in the quiz below I am trying to make questions of a quiz to be validated and alert at the end of quiz how many correct questions I had and also I do not want to refresh the page when I press the button Submit, tried to see why it refreshes and honestly have no idea why it refreshes?
https://codepen.io/beh4r/pen/mgKmmd

#2

The default behavior when an input of type=“submit” will attempt to submit a form (if nested inside a form). Forms have an action attribute which is used to tell the form where to be submitted. Your form does not specify an action, so the default is to just reload the current page the form is on. To do something specific when the input with type=“submit” is clicked, you will need to create an event listener for the input and then prevent the default behavior of the input submitting the form (search preventDefault method) and then write code for what you want to do instead when the input is clicked. Another approach is to create an event listener for “submit” and do something similar.

1 Like
#3

Yeah fixed it by using preventDefault with an event listener, thanks.
But any idea why quiz results doesn’t show on submit in an alert window ?
And if I skip question and not choose any answer from question It doesn’t show any error or any alert to select any option from answer ?

#4

Can you please update the pen with your latest changes?

#5

updated it now as I forgot to update it besides my visual code

#6

Your click event handler for the input only prevents the form from submitting. If you want some other code to run (i.e call a function), you need to do that inside it.

Why not prevent the user from going forward until selecting an answer?

#7

This is the code and it alerts if I skip question without choosing an option ?

   for (i = 1; i <= total; i++) { 
      if (eval("q"+i) === null || eval("q"+i) === "") {
          alert("You missed question" +i)
          return false
      }
   }
#8

Yes and it is inside a function which you could call when the input with type=“submit” is clicked.

#9

Oh I see looks like I have to make an if statement for button Next when when i do not choose any options and for submit too to show results on Submit.

#10

https://codepen.io/beh4r/pen/joPmKd
Anyone can help me with quiz on Submit button, because I’ve got only submit button left to do and i tried my best but there’s an error with questions that always it shows 0/4 everytime I choose the correct answer. And on Submit it does not show alert immediately but it shows the alert “Choose an option” 4 times then it shows the results of quiz, any idea ?

#11

You are getting 4 alerts, because when you click the Submit button, you call returnScore which then calls getScore (inside the alert) and getScore calls validateForm 4 times because it is inside a for loop which iterates through the answers array. Those 4 alerts will show before the final alert because those other calls must be evaluated to return a result to the alert inside returnScore.

You need to add a console.log statement before you if statement inside the for loop of getScore. Your validateForm function returns a Boolean value and answers[i] will be a string value, so those will never be equal.

#12

I tried different way by just putting the questions and score in a single function and now it doesn’t even show alert on Submit and I’ve been stuck with this honestly.
If you could help me with this quiz with submit showing score would be very good for me so I could learn what you did because me as a beginner don’t have no solution for this, thank you.
https://codepen.io/beh4r/pen/joPmKd

#13

@behari97 input elements do not have onsubmit events. However, they do have onclick events. You need to change your submitAnswer function’s fist 3 lines to the following. You will notice an event parameter was added. That was so you can pass the event object from the onclick event and then prevent the form from actually submitting (i.e going to another page or reloading the page in this case).

function submitAnswer(event){
    event.preventDefault();
    let total = 4;
    let score = 0;

Also, in the input element, you will need to pass the event object like:

<input id="bot-submit" type="submit" value="Submit" onclick="submitAnswer(event);"/>

Once you fix this, you will notice a new error involving the fact that q1 is not defined. q1 and the other 3 elements in the questions array are not defined anywhere in your code, so you will need to do that somewhere. Based on your current comparison logic in the for loop of the submitAnswer function, the questions array should contain the answers received in the various inputs. You might want to rename that array to something like userAnswers to make it clear what you are comparing there. Also, I might recommend renaming the answers array to something like correctAnswers to make it clear those are the correct answers you are comparing to the user’s answers.

#14

About submitAnswer added the event and it prevents from reloading on submit.
And about questions, I added them into an array with questions and answers and replaced answers with correctAnswers as you said but it shows an error on Console Log saying “correctAnswers is not defined”, any idea why it shows that? Is because I added answers and questions in an array or what?
https://codepen.io/beh4r/pen/joPmKd

#15

One of the things you are currently missing in your code is a way to capture the user’s selections. To get the user’s answer for each question, you are going to need to due some research about how to capture which radio button was selected for each question. One possible way (of many ways) would be to create an empty array (let’s call it usersAnswers) and push user’s selected index of options into this array after each click of Next and the click of Submit

If you can create an array containing which index of the options that was clicked, then based on recent changes to the questions array, you are going to need to make changes inside the for loop of submitAnswer.

    for (i = 0; i < questions.length; i++) {
      let correctAnswerIndex = questions[i].correctAnswers;
      if (correctAnswerIndex === userAnswers[i]) {
        score++;
      }
    }

FYI - Once you figure out the logic for collecting the userAnswers, you also need to know that your current quiz still allows you to click Submit at the end without selecting an option. That is because you only called validateForm when a Next button is clicked. You will need to add an if statement in submitAnswer (after the event.preventDefault() to validate the last question has been answered before proceeding with the rest of the code.

#16

Added an if statement on submitAnswer and now it shows always please select an option even that i have my if statement that checks if any option is checked or not?
https://codepen.io/beh4r/pen/joPmKd

#17

Remember, your inline onsubmit is going to pass the event object (not a number) to submitAnswer. I suggest going back to what you had before your latest changes and try to implement what I talked about in my previous reply. I don’t see where you have defined a userAnswers array or attempting to push the the option index for the selected option when the Next or Submit buttons are clicked.

I will give you another hint of where you can add the the actually push statement (see below):

userAnswers.push(i);

Think about the one place in your existing code (think validateForm) where you check if an option has been checked. validateForm gets called when the Next button is clicked, but not when the Submit button is clicked, so you will just need to make sure you call validateForm in the appropriate place in submitAnswer function.

#18

About array of userAnswers I made a mistake and removed lines for that, so you have it on Codepen now.
And about validateForm to do the one for the submit button, I added same code from Next button because I had no idea what to change from that line of codes for Next button to Submit button because I thought the same code would work for Submit but still it shows “Select an option” and on Console Log it doesn’t show any error?
If you could solve this error with my button on Submit that doesn’t show results and “Select an option”, would be very thankful because I think I’ve mostly wasted your time because every time you told me to do I just messed up more and more and I am pretty bad with JavaScript honestly.
https://codepen.io/beh4r/pen/joPmKd