jckly
jckly

Reputation: 851

Jquery can't get else if to work

I'm writing a jquery quiz.

First I'm setting the variable depending on the page:

  if ($("body").hasClass("questionone")){
  var $currentQuestion = 1;
  console.log($currentQuestion);
  }
  else if ($("body").hasClass("questiontwo")){
    var $currentQuestion = 2;
    console.log($currentQuestion);
  }
  else if ($("body").hasClass("questionthree")){
    var $currentQuestion = 3;
    console.log($currentQuestion);
  };

Then when they answer a question I have a pop up that says incorrect or correct and a button that says next question. The next question button re-directs dependant on what the currentQuestion variable is. The problem is it works for the if part and re-directs from question 1 to question 2 on click but on question 2 it doesn't re-direct to question 3.

Here is the redirect code:

  $(".nextquestion").on("click", function(){
    if( $currentQuestion = 1 ) {
      window.location.href = "question2.html";
    }
    else if( $currentQuestion = 2 ) {
      console.log("thisworks"); 
      window.location.href = "question3.html";
    } 
    else if( $currentQuestion = 3 ) {
      window.location.href = "question4.html";
    };
  });

Thanks for any help.

Upvotes: 0

Views: 57

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382122

Change your = to == or ===, so that you don't assign but just compare :

if( $currentQuestion === 1 ) {
...
else if( $currentQuestion === 2 ) {
...
else if( $currentQuestion === 3 ) {

And please avoid repeating the var declaration (var $currentQuestion = 2;), it makes the code hard to decipher.

Upvotes: 4

Chirag Sutariya
Chirag Sutariya

Reputation: 362

if ($("#body").hasClass("questionone")){
  var $currentQuestion = 1;
  console.log($currentQuestion);
  }
  else if ($("#body").hasClass("questiontwo")){
    var $currentQuestion = 2;
    console.log($currentQuestion);
  }
  else if ($("#body").hasClass("questionthree")){
    var $currentQuestion = 3;
    console.log($currentQuestion);
  };

$(".nextquestion").on("click", function(){
    if( $currentQuestion == 1 ) {
      window.location.href = "question2.html";
    }
    else if( $currentQuestion == 2 ) {
      console.log("thisworks"); 
      window.location.href = "question3.html";
    } 
    else if( $currentQuestion == 3 ) {
      window.location.href = "question4.html";
    };
  });

try this

Upvotes: 0

Related Questions