Home > OS >  Text based JavaScript Ajax quiz
Text based JavaScript Ajax quiz

Time:01-22

I'm trying to create a text based quiz that moves on to the next slide when the correct answer is guessed. I have the code running(which is not showing questions in my pc but it is showing the questions perfectly here) but the input space is not displaying on my output screen. Can someone please help me identify the error?

Base code is from https://codepen.io/SitePoint/pen/GmPjjL

(function(){
    // Functions
    function buildQuiz(){
      // variable to store the HTML output
      const output = [];
  
      // for each question...
      myQuestions.forEach(
        (currentQuestion, questionNumber) => {
  
          // variable to store the list of answers
          const answers = [];

          for(questionNumber in currentQuestion.answers){

        
            answers.push(
              `<label>
                <input type="text" name="question${questionNumber}" placeholder="Company" size="20">
              </label>`
              
            );
          }
  
          // add this question to the output
          output.push(
            `<div >
              <div > ${currentQuestion.question} </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 userAnswer = (answerContainer.querySelector('input').value);
        
        //if answer is blank
    if (userAnswer.length === 0 ) {
        alert("You must enter an answer to continue...");
        return false;
    }

        // if answer is correct
        if(userAnswer.toLowerCase() === currentQuestion.correctAnswer.toLowerCase()){
          // add to the number of correct answers
          numCorrect  ;
  
          // alert
         alert("CONGRATULATIONS! Your answer is correct! You have advanced to the next level.");
        }
        // if answer is wrong
        else{
          // alert
          alert("Wrong answer, please, keep trying...");
        }
      });
  
      // 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';
      }
      else{
        nextButton.style.display = 'inline-block';
        submitButton.style.display = 'none';
      }
    }
  
    function showNextSlide() {
      showSlide(currentSlide   1);
    }
  
    function showPreviousSlide() {
      showSlide(currentSlide - 1);
    }
  
    // Variables
    const quizContainer = document.getElementById('quiz');
    const resultsContainer = document.getElementById('results');
    const submitButton = document.getElementById('submit');
    
    const myQuestions = [
    {
      question: "Who invented JavaScript?",
      image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
      answers: "Write your answer here",
      correctAnswer: "Nike",
    },
    {
      question: "Which one of these is a JavaScript package manager?",
      image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
      correctAnswer: "Nike",

    },
    {
      question: "Which tool can you use to ensure code quality?",
      image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
      correctAnswer: "Nike",
    }
];
    // Kick things off
    buildQuiz();
  
    // Pagination
    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;
  
    // Show the first slide
    showSlide(currentSlide);
  
    // Event listeners
    submitButton.addEventListener('click', showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
  })();
  
@import url(https://fonts.googleapis.com/css?family=Work Sans:300,600);

body{
    font-size: 20px;
    font-family: 'Work Sans', sans-serif;
    color: #333;
  font-weight: 300;
  text-align: center;
  background-color: #f8f6f0;
}
h1{
  font-weight: 300;
  margin: 0px;
  padding: 10px;
  font-size: 20px;
  background-color: #444;
  color: #fff;
}
.question{
  font-size: 30px;
  margin-bottom: 10px;
}
.answers {
  margin-bottom: 20px;
  text-align: left;
  display: inline-block;
}
.answers label{
  display: block;
  margin-bottom: 10px;
}
button{
  font-family: 'Work Sans', sans-serif;
    font-size: 22px;
    background-color: #279;
    color: #fff;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
button:hover{
    background-color: #38a;
}





.slide{
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.5s;
}
.active-slide{
  opacity: 1;
  z-index: 2;
}
.quiz-container{
  position: relative;
  height: 200px;
  margin-top: 40px;
}
    <!DOCTYPE html>
<html>
<head><title>trial</title>
  <link rel="stylesheet" href="trialcs.css">
<style>
            .color-cell {
                color: white;
            }
        </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="logojs.js"></script>
</head>
<body>

If I give you color wheel of 5 most dominant colors from 5 iconic logos, how many can you guess?
<div >
  <div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
<script src="logocanvas.js"></script>
</body>

</html>

  

CodePudding user response:

In your output.push I've added a input box, you need to pass your input box in this particular place. Input box I've added is just to show you the place you can add Input tag.

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

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // variable to store the list of answers
            const answers = [];

            for (questionNumber in currentQuestion.answers) {
                answers.push(
                    `<label>
                <input type="text" name="question${questionNumber}" placeholder="Company" size="20">
              </label>`
                );
            }

            // add this question to the output
            output.push(
                `<div >
              <div > ${currentQuestion.question} </div>

                            
                <input type="text" name="question${questionNumber}" placeholder="Write answer here" size="20">
            </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 userAnswer = answerContainer.querySelector("input").value;

            //if answer is blank
            if (userAnswer.length === 0) {
                alert("You must enter an answer to continue...");
                return false;
            }

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

                // alert
                alert(
                    "CONGRATULATIONS! Your answer is correct! You have advanced to the next level."
                );
            }
            // if answer is wrong
            else {
                // alert
                alert("Wrong answer, please, keep trying...");
            }
        });

        // 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";
        } else {
            nextButton.style.display = "inline-block";
            submitButton.style.display = "none";
        }
    }

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

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

    // Variables
    const quizContainer = document.getElementById("quiz");
    const resultsContainer = document.getElementById("results");
    const submitButton = document.getElementById("submit");

    const myQuestions = [
        {
            question: "Who invented JavaScript?",
            image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
            answers: "Write your answer here",
            correctAnswer: "Nike"
        },
        {
            question: "Which one of these is a JavaScript package manager?",
            image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
            answers: "Write your answer here",
            correctAnswer: "Nike"
        },
        {
            question: "Which tool can you use to ensure code quality?",
            image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
            answers: "Write your answer here",
            correctAnswer: "Nike"
        }
    ];
    // Kick things off
    buildQuiz();

    // Pagination
    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;

    // Show the first slide
    showSlide(currentSlide);

    // Event listeners
    submitButton.addEventListener("click", showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
})();
@import url(https://fonts.googleapis.com/css?family=Work Sans:300,600);

body {
    font-size: 20px;
    font-family: "Work Sans", sans-serif;
    color: #333;
    font-weight: 300;
    text-align: center;
    background-color: #f8f6f0;
}
h1 {
    font-weight: 300;
    margin: 0px;
    padding: 10px;
    font-size: 20px;
    background-color: #444;
    color: #fff;
}
.question {
    font-size: 30px;
    margin-bottom: 10px;
}
.answers {
    margin-bottom: 20px;
    text-align: left;
    display: inline-block;
}
.answers label {
    display: block;
    margin-bottom: 10px;
}
button {
    font-family: "Work Sans", sans-serif;
    font-size: 22px;
    background-color: #279;
    color: #fff;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
button:hover {
    background-color: #38a;
}

.slide {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    z-index: 1;
    opacity: 0;
    transition: opacity 0.5s;
}
.active-slide {
    opacity: 1;
    z-index: 2;
}
.quiz-container {
    position: relative;
    height: 200px;
    margin-top: 40px;
}
If I give you color wheel of 5 most dominant colors from 5 iconic logos, how many can you guess?
<div >
    <div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>

  •  Tags:  
  • Related