Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - Submit button that shows the score

Below it's my code with a quiz of 4 questions and with a "Submit" button in the last question and I tried to add some code that on Submit it will show an alert with the results of the quiz about how many questions I got correct. But there are some errors with my code that when I press Submit it doesn't show results of the quiz and it still shows me "Select an option", even that I've selected an option from the question and I've added an if statement to Submit button so it will check if any option is selected or not, but even If I select any option it still shows me that alert ?

let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');

for (let i = 0; i < nextButtons.length; i++) {
  let nextQuestion = nextButtons[i];
  nextQuestion.onclick = function() {

    if (validateForm(i + 1)) {
      switchToNextQuestion(this);
    }
  }
}

function switchToNextQuestion(nextQuestion) {
  let parentId = nextQuestion.parentNode.id;
  if (parentId === 'pytja1') {
    question1.style.display = 'none';
    question2.style.display = 'block';
  } else if (parentId === 'pytja2') {
    question2.style.display = 'none';
    question3.style.display = 'block';
  } else if (parentId === 'pytja3') {
    question3.style.display = 'none';
    question4.style.display = 'block';
  }
}

function validateForm(elementNumber) { // elementnumber gets radio name from multiple questions
  let radios = document.getElementsByName("q" + elementNumber);
  let formValid = false;
  let i = 0;
  while (!formValid && i < radios.length) {
    if (radios[i].checked) formValid = true;
    i++;
  }
  if (!formValid) alert("Select one option");
  return formValid;
}

let questions = [{
    question: "I am a ?",
    userAnswers: ["Male", "Female", "Other"],
    correctAnswers: 0,
  },
  {
    question: "Football has letters ?",
    userAnswers: [8, 5, 6],
    correctAnswers: 0,
  },
  {
    question: "VW stands for ?",
    userAnswers: ["BMW", "Volkswagen", "Audi"],
    correctAnswers: 1,
  },
  {
    question: "What year is it ?",
    userAnswers: [2017, 2015, 2019],
    correctAnswers: 2,
  }
];

function submitAnswer(elementNumber) {
  let radios = document.getElementsByName("q" + elementNumber);
  let formValid = false;
  let i = 0;
  while (!formValid && i < radios.length) {
    if (radios[i].checked) formValid = true;
    i++;
  }
  if (!formValid) alert("Select one option");
  return formValid;

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

  if (score != total) {
    alert("You got " + score + " out " + total)
  }
  if (score === total) {
    alert("Congratulation your score " + score + " out of " + total);
  }
  let results = document.getElementById('results')
  alert("you")
}
document.getElementById("bot-submit").addEventListener("click",
  function(e) {
    e.preventDefault();
  })
form {
  width: 100%;
  position: relative;
  float: left;
  padding-top: 50px;
}

.quiz {
  margin: 0px auto;
  width: 250px;
  height: 100px;
  position: absolute;
  top: 60px;
  left: 42%;
}

.quest1,
.quest2,
.quest3,
.quest4 {
  background-color: cadetblue;
  font-size: 22px;
}

.questions1 {
  margin-left: 28px;
  background-color: cyan;
  width: 220px;
  padding: 10px;
  font-size: 20px;
}

.questions2 {
  background-color: red;
}

.questions3 {
  background-color: greenyellow;
}

.questions4 {
  background-color: olivedrab;
}

.bot {
  margin-top: 10px;
}

#pytja2,
#pytja3,
#pytja4 {
  margin-left: 28px;
  display: none;
  width: 220px;
  padding: 10px;
  font-size: 20px;
}
<form id="quiz-form">
  <div di="results"></div>
  <div class="quiz">
    <div id="pytja1" class="questions1">
      <span class="quest1">I am a ?</span><br/>
      <input type="radio" name="q1" value="male" id="correct"> Male<br/>
      <input type="radio" name="q1" value="female" id="correct2"> Female<br/>
      <input type="radio" name="q1" value="other" id="correct3"> Other<br/>
      <input class="bot" type="button" value="Next" "/>
          </div>
          <div id="pytja2 " class="questions2 ">
            <span class="quest2 ">Football has letters ?</span><br/>
            <input type="radio " name="q2 " value="8 " class="correct "> 8<br/>
            <input type="radio " name="q2 " value="5 "> 5<br/>
            <input type="radio " name="q2 " value="6 "> 6<br/>
            <input class="bot " type="button " value="Next ""/>
    </div>
    <div id="pytja3" class="questions3">
      <span class="quest3">VW stands for ?</span><br/>
      <input type="radio" name="q3" value="BMW" /> BMW <br/>
      <input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
      <input type="radio" name="q3" value="Audi" /> Audi<br/>
      <input class="bot" type="button" value="Next" "/>
          </div>
          <div id="pytja4 " class="questions4 ">
            <span class="quest4 ">What year we are ?</span><br/>
            <input type="radio " name="q4 " value="2017 " /> 2017<br/>
            <input type="radio " name="q4 " value="2015 " /> 2015<br/>
            <input type="radio " name="q4 " value="2019 " class="correct " /> 2019<br/>
            <input id="bot-submit " type="submit " value="Submit " onclick="submitAnswer(); "/>
          </div>
        </div>
      </form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned above, your code has some errors but I have written snippets that will achieve your aim with shorter syntax.

//Javascript code
let questionss = [{
    question: "I am a ?",
    options: ["Male", "Female", "Other"],
    correctAnswers: 'Male',
  },
  {
    question: "Football has letters ?",
    options: [8, 5, 6],
    correctAnswers: 8,
  },
  {
    question: "VW stands for ?",
    options: ["BMW", "Volkswagen", "Audi"],
    correctAnswers: 'Volkswagen',
  },
  {
    question: "What year is it ?",
    options: [2017, 2015, 2019],
    correctAnswers: 2019,
  }
];

let questionText = document.getElementById('cd-questions');
let optiontext = document.querySelectorAll('.optiontext');
let options = document.querySelectorAll('.options');
let nextBtn = document.getElementById('next-btn');
let currentQuestion = 0;
var score = 0;
var checkedStatus = false;


setQuestion(currentQuestion); // set default question

nextBtn.addEventListener('click', e => {
  e.preventDefault();
  if (valForm()) setQuestion(currentQuestion); //validates and next question
});

function setQuestion(currentQuestion) {
  questionText.innerText = questionss[currentQuestion].question; //set current question to the DOM

  for (let i = 0; i < 3; i++) {
    options[i].value = questionss[currentQuestion].options[i]; //set options  value for current question

    optiontext[i].innerText = questionss[currentQuestion].options[i]; //set options for current question

  }
}

function valForm() {
  for (let i = 0; i < 3; i++) {
    if (options[i].checked) {
      let userans = options[i].value;
      if (questionss[currentQuestion].correctAnswers == userans) {
        score++;
      }

      options[i].checked = false;
      if (currentQuestion < questionss.length - 1) {

        currentQuestion++;
        if (currentQuestion == questionss.length - 1) {
          nextBtn.innerText = 'Submit';
        }
      } else {
        alert('Your total score is ' + score);
        currentQuestion = 0;
        nextBtn.innerText = 'Start';
      }
      return true;
    }
  }
  if (checkedStatus == false) {
    alert('please choose an answer');
    setQuestion(currentQuestion);
  }

  return false;
}
<form>
  <div id="cd-questions"></div>
  <input class="options" name="answer" type="radio" />
  <span class="optiontext"></span>
  <input class="options" name="answer" type="radio" />
  <span class="optiontext"></span>
  <input class="options" name="answer" type="radio" />
  <span class="optiontext"></span>
  <div>
    <button id="next-btn">Next</button>
  </div>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...