提交按钮,显示分数

时间:2019-05-12 21:22:52

标签: javascript

下面是我的代码,其中包含4个问题的测验,并在最后一个问题中带有“提交”按钮,我尝试添加一些代码,使其在Submit上将显示有关我有多少个问题的测验结果的警报正确了。 但是我的代码存在一些错误,当我按Submit时,它不显示测验的结果,并且仍然显示“选择选项”,即使我从问题中选择了一个选项,并且添加了一个如果声明“提交”按钮,它将检查是否选择了任何选项,但是即使我选择了任何选项,它仍然会向我显示警报?

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>

2 个答案:

答案 0 :(得分:1)

如上所述,您的代码有一些错误,但是我编写了一些片段,这些片段将以较短的语法实现您的目标。

//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>

答案 1 :(得分:1)

我很高兴它奏效。我想相信您的其他问题来自第二个循环。

for (let i = 0; i < 3; i++) {
if (options[i].checked) { //iterates through the radio buttons for the checked option
  let userans = options[i].value; // get the value of the checked 
  if (questionss[currentQuestion].correctAnswers == userans) {
    score++; //increment score by 1 if the chosen answer is the correct answer
  }
  options[i].checked = false; //reset button to avoid next question being checked by 
  default.
  if (currentQuestion < questionss.length - 1) {

    currentQuestion++; // increment current question index
    if (currentQuestion == questionss.length - 1) {
      nextBtn.innerText = 'Submit'; // Changed submit button text if it's the last question.
    }
  } else {
    alert('Your total score is ' + score);
    currentQuestion = 0;
    nextBtn.innerText = 'Start';
  }
  return true; // return true which was  tested when the function was involked before nexting the question.
}
}

我希望有帮助。