jward01
jward01

Reputation: 759

Super simple quiz program. My answers are not validating and score isn't ++ either

I am writing this super simple javascript quiz for practice. I am frustrated because I think my code is correct, but my code is not working.

My answers are not 'validating' and I have no clue why. My score is still coming out as 0. My score is not score++ when it should..

The problem is in this snippet:

 for (var j = 0; j <= total.length; j++) {
    if (questionArray[j] === answers[j]) {
      score = score + 1;
    }
  }

JS:

function submitAnswers() {

  //Set score and total number of questions
  var total = 5;
  var score = 0;
  //Get user input for each question
  var q1 = document.forms['quizForm']['q1'].value.toString();
  var q2 = document.forms['quizForm']['q2'].value.toString();
  var q3 = document.forms['quizForm']['q3'].value.toString();
  var q4 = document.forms['quizForm']['q4'].value.toString();
  var q5 = document.forms['quizForm']['q5'].value.toString();

  //Load Questions into Question Array
  var questionArray = [q1, q2, q3, q4, q5];

  //Validation
  for (var i = 0; i <= questionArray.length; i++) {
    if (questionArray[i] === null || questionArray[i] === '') {
      alert("Oops!  You forgot to answer a question.  Please enter an answer for Question " + [i + 1] + ".");
      return false;
    }
  }


  //Set correct Answers
  var answers = ["b", "a", "d", "b", "d"];

  //Check for correct answers
  for (var j = 0; j <= total.length; j++) {
    if (questionArray[j] === answers[j]) {
      score = score + 1;
    }
  }
  alert("You scoreed "+ score+ " out of "+total);



  return false;
}

JSFiddle: https://jsfiddle.net/jeffward01/1y3dxk0s/

Upvotes: 0

Views: 152

Answers (2)

j08691
j08691

Reputation: 208002

Change:

for (var j = 0; j < total.length; j++) {

to

for (var j = 0; j < total; j++) {

total is the value you want, not total.length.

jsFiddle example

Upvotes: 1

user2844991
user2844991

Reputation:

for validation part:

  for (var i = 0; i <= questionArray.length; i++)

should be

  for (var i = 0; i < questionArray.length; i++)

for answers part:

 for (var j = 0; j <= total.length; j++)

should be

 for (var j = 0; j < answers.length; j++)

Upvotes: 2

Related Questions