0

I'm working on a quiz type thing for Javascript - I have a input form set up that disappears after I click the submit button to show the quiz questions, along with the previous/next/submit/reset buttons. However when I try to submit to get the questions to appear - nothing shows up and it only reloads the page. I have tried to fix this problem all day, and have came up with nothing. I would appreciate if anyone could help put me into the right direction into fixing this?

HTML file

<!DOCTYPE html>
<html>

<head>

    <title>canada quiz</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/css.css">
    <script src="js/js.js"></script>
</head>

<body>

  <div id="form">
    <form id="quizform">
        <label for="name">Enter Your Name: <span id="nameMsg"></span></label> 
        <input type="text" id="name" placeholder="Your name here" required autofocus>
        <br><br>
        <label for="age">Enter Your Age: <span id="ageMsg"></span></label>                     
        <input type="number" value="" required placeholder="Your age here">
        <BR><BR>
        <input type="submit" id="submit" value="START YOUR QUIZ" >
        <input type="button" id="formReset" value="reset" ><br>
    </form>
</div>

    <br>

<div id="welcome"></div>
<form id="questions">
    <div class="quiz-container">
        <div id="quiz"></div>
    </div>
    <button id="previous">Previous Question</button>
    <button id="next">Next question</button>
    <br>
    <button id="submit">Submit Quiz</button>
    <button id="reset">Reset Quiz</button>
    <div id="results"></div>
</form>

</body>
</html>

JS FILE

window.addEventListener("load", function () {

  // loginForm.style.display = "block";
  // quizForm.style.display = "none";
  // nextButton.style.display = "none";

    document.getElementById("submit").addEventListener("click", buildQuiz);

  let previousButton = document.getElementById("previous");
  let nextButton = document.getElementById("next");
  let slides = document.querySelectorAll(".slide");
  let quizContainer = document.getElementById('quiz');
  let resultsContainer = document.getElementById('results');
  let submitButton = document.getElementById('submit');
  let resetButton = document.getElementById('reset');
  let currentSlide = 0;

    nextButton.style.display = "none";
    previousButton.style.display = 'none';
    submitButton.style.display = 'none';
    resetButton.style.display = 'none';

  // let previousButton = document.getElementById("previous").style.display = "none";
  // document.getElementById("next").style.display = "none";
  // document.getElementById("submit").style.display = "none";
  // document.getElementById("reset").style.display = "none";
  
    let loginForm         = document.getElementById("login");
  let quizForm          = document.getElementById("questions");
  let ageMsg          = document.getElementById("ageMsg");
  
    // let submitButton      = document.getElementById("submit");
    let errorMsg          = document.getElementById("nameMsg");
    let error             = document.getElementById("error");


  // Functions
  function buildQuiz(){
    // variable to store the HTML output
    const output = [];

    // for each question...
    myQuestions.forEach(
      (currentQuestion, questionNumber) => {

        // variable to store the list of possible answers
        const answers = [];

        // and for each available answer...
        for(letter in currentQuestion.answers){

          // ...add an HTML radio button
          answers.push(
            `<label>
              <input type="radio" name="question${questionNumber}" value="${letter}">
              ${letter} :
              ${currentQuestion.answers[letter]}
            </label>`
          );
        }

        // add this question and its answers to the output
        output.push(
          `<div class="slide">
            <div class="question"> ${currentQuestion.question} </div>
            <div class="answers"> ${answers.join("")} </div>
          </div>`
        );
      }
    );

    // finally combine our output list into one string of HTML and put it on the page
    quizContainer.innerHTML = output.join('');
  }

  function showResults(){

    // gather answer containers from our quiz
    const answerContainers = quizContainer.querySelectorAll('.answers');

    // keep track of user's answers
    let numCorrect = 0;

    // for each question...
    myQuestions.forEach( (currentQuestion, questionNumber) => {

      // find selected answer
      const answerContainer = answerContainers[questionNumber];
      const selector = `input[name=question${questionNumber}]:checked`;
      const userAnswer = (answerContainer.querySelector(selector) || {}).value;

      // if answer is correct
      if(userAnswer === currentQuestion.correctAnswer){
        // add to the number of correct answers
        numCorrect++;

        // color the answers green
        answerContainers[questionNumber].style.color = 'lightgreen';
      }
      // if answer is wrong or blank
      else{
        // color the answers red
        answerContainers[questionNumber].style.color = 'red';
      }
    });

    // show number of correct answers out of total
    resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
  }

  function showSlide(n) {
    slides[currentSlide].classList.remove('active-slide');
    slides[n].classList.add('active-slide');
    currentSlide = n;
    if (currentSlide === 0) {
      previousButton.style.display = 'none';
    }
    else {
      previousButton.style.display = 'inline-block';
    }
    if (currentSlide === slides.length-1){
      nextButton.style.display = 'none';
      submitButton.style.display = 'inline-block';
      resetButton.style.display = 'inline-block';
    }
    else {
      nextButton.style.display = 'inline-block';
      submitButton.style.display = 'none';
      resetButton.style.display = 'none';
    }
  }

  function showNextSlide() {
    showSlide(currentSlide + 1);
  }

  function showPreviousSlide() {
    showSlide(currentSlide - 1);
  }

  // Variables

  const myQuestions = [

    {
      question: "The capital city of Canada is",
      answers: {
        a: "Ottawa",
        b: "Toronto",
        c: "Montreal",
        d: "Vancouver"
      },
      correctAnswer: "a"
    },

    {
      question: "Canada's main language is", 
      answers: {
        a: "English",
        b: "Spanish",
        c: "French",
        d: "Italian"
      },
      correctAnswer: "a"
    },

    {
      question: "The largest city in Canada is", 
      answers: {
        a: "Toronto",
        b: "Vancouver",
        c: "Quebec City",
        d: "Calgary"
      },
      correctAnswer: "a"
    },

    {
      question: "How many provinces does Canada have?", 
      answers: {
        a: "10",
        b: "12",
        c: "13",
        d: "15"
      },
      correctAnswer: "c"
    },

    {
      question: "The smallest province in Canada is", 
      answers: {
        a: "Nunavut",
        b: "Prince Edward Island",
        c: "Nova Scotia",
        d: "Newfoundland"
      },
      correctAnswer: "b"
    },

    {
      question: "The leader of Canada is known as", 
      answers: {
        a: "The President",
        b: "King",
        c: "Prime Minster",
        d: "Premier"
      },
      correctAnswer: "c"
    },

    {
      question: "The first inhabitants of Canada were the", 
      answers: {
        a: "Vikings",
        b: "Natives",
        c: "French",
        d: "English"
      },
      correctAnswer: "b"
    },

    {
      question: "Which animal is the symbol of Canada?", 
      answers: {
        a: "Moose",
        b: "Eagle",
        c: "Goose",
        d: "Beaver"
      },
      correctAnswer: "d"
    },

    {
      question: "Which plant is the symbol of Canada?", 
      answers: {
        a: "Vine Maple",
        b: "Oak Leaf",
        c: "Hornbeam Maple",
        d: "Maple Leaf"
      },
      correctAnswer: "d"
    },
    {
      question: "What year did Canada become a country?", 
      answers: {
        a: "1890",
        b: "1867",
        c: "1874",
        d: "1900"
      },
      correctAnswer: "b"
    },
    {
      question: "How many oceans does Canada touch?", 
      answers: {
        a: "2",
        b: "3",
        c: "4",
        d: "5"
      },
      correctAnswer: "b"
    }
  ];

  // Kick things off
  buildQuiz();

  // Pagination

  // Show the first slide
  showSlide(currentSlide);

  // Event listeners
  submitButton.addEventListener('click', showResults);
  resetButton.addEventListener('click', function(e) {location.reload();});
  previousButton.addEventListener("click", showPreviousSlide);
  nextButton.addEventListener("click", showNextSlide);
})();

BeR
  • 61
  • 6
  • On the order of "is it plugged in?" — a submit button in a form _submits_ the form to the server at the url specified by the _action_ attribute. Since you have no action attribute it submits the form to the _current_ url (submit to itself) and doing that _reloads_ the page, wiping out fields contents and any javascript state. If you don't want that submit to happen you have to catch the form submit event and `.preventDefault()` the event. – Stephen P Nov 17 '20 at 01:21
  • @StephenP I think my issue is more that I don't have a function to call the questions, so how could I call the questions to the submit button? – BeR Nov 17 '20 at 01:26
  • Trying to use your code I get errors in my browser console, first `Uncaught TypeError: window.addEventListener(...) is not a function` and then `Uncaught TypeError: slides[currentSlide] is undefined` — If I change it from _window_ to _document_ I still get `Uncaught TypeError: document.addEventListener(...) is not a function` (now "document") but it otherwise starts to look right. If I click on "Start your Quiz" I get the form submit behavior I mentioned — the page submits and therefore re-loads. – Stephen P Nov 17 '20 at 01:51
  • @StephenP - is there any solution to fix the form submit behavior to have the questions to appear? I really am at a loss here. If I remove the display none codes for the next/previous/submit/reset buttons, everything works as planned but not the forms. – BeR Nov 17 '20 at 01:57
  • To fix the submit you must, as I said before, use `event.preventDefault()`. For example `function showResults()` should take a parameter `function showResults(e)` where `e` is the _event_ that is passed to the event handler. Then you can `e.preventDefault()` to prevent the normal (submit) handling of the event. _Another_ problem is that you have more than one thing with `id="submit"` — an `` and a ` – Stephen P Nov 17 '20 at 17:17
  • You have `document.getElementById("submit").addEventListener("click", buildQuiz)` but then you _**also**_ call `buildQuiz()` (with the comment "Kick things off"). After that explicit call to buildQuiz you do `showSlide(currentSlide);` but `currentSlide` isn't defined. It _looks_ like it is, but the scope is wrong. `slides[currentSlide]` is undefined because when `let slides = document.querySelectorAll(".slide")` is called you haven't called buildQuiz yet, so no `
    ` exists yet. Do you know how to use the browser debugger? There is too much wrong for me to debug this _for_ you.
    – Stephen P Nov 17 '20 at 17:52
  • This is more confusing than necessary because you wrap the whole thing in `window.addEventListener("load", function()...` which you don't have to do (any more) and which confuses things with the scope of variables. Just use the "defer" attribute `` or move your script tag out of the head and put it at the end of the body, just before the `

    ` tag. **Read [this stackoverflow answer](https://stackoverflow.com/a/24070373/17300)**

    – Stephen P Nov 17 '20 at 18:00

0 Answers0