Skip to content
Advertisement

How do I build a text 3 question input quiz that redirects on correct answer using JavaScript?

StackOverflow community. I am hoping to help out a friend by fixing the script below to enable it to run.

I can see a few errors myself but it’s my first time writing more than echo “Hello World!”;.

I would like 3 questions and if all correct, a congradulate box apears “you got all 3 correct, move on” then a redirect to another page.

If incorrect, “Incorrect, try again!”

I also tried to add upper or lower case for the answers but failed.

Can anyone help me tidy it up and enable it to function or point me in the right direction.

Many thanks in advance.

<!DOCTYPE html>
<html>
<head>
        <title>JavaScript fill in the blanks</title>
</head>
<body>
<form name="CRYPTIC RESCUE MISSION">
Q.The answer is Question 1?
<br><input type="text" name="q1"><br></br>

Q.The answer is Question 2?
<br><input type="text" name="q2"><br></br>

Q.The answer is Question 3?
<br><input type="text" name="q3"><br></br>

<input type="button" value="submit" onclick="myfun()">
</form>
</body>
<script type="text/javascript">

function myfun(){
        var v1=document.myform.value;
        var v2=document.myform.q2.value;
        var v3=document.myform.q3.value;
        
        var score=0;
        
        if(v1=="Answer 1"){
                score++;
        }
        if(v2=="Answer 2"){
                score++;
        }
        if(v3=="Answer 3"){
                score++;
        }
        
        alert("you got all "+score"correct, move on");
        location.href = 'https://google.co.uk';
        
        else
        alert("Incorrect, try again!");
        
        
}
</script>


</html>

Advertisement

Answer

I think this should solve your problem. ( Please compare your submission with this answer so you can see what you where missing

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript fill in the blanks</title>
  </head>
  <body>
    <form name="CRYPTIC RESCUE MISSION">
      Q.The answer is Question 1?
     <br><input type="text" name="q1"><br></br>

     Q.The answer is Question 2?
    <br><input type="text" name="q2"><br></br>

    Q.The answer is Question 3?
    <br><input type="text" name="q3"><br></br>

    <input type="button" value="submit" onclick="myfun()">
  </form>
</body>
<script type="text/javascript">

  function myfun(){
    var v1 = document.getElementsByName('q1')[0].value;
    var v2 = document.getElementsByName('q2')[0].value;
    var v3 = document.getElementsByName('q3')[0].value;
    
    var score=0;
    
    if(v1=="Answer 1"){
            score++;
    }
    if(v2=="Answer 2"){
            score++;
    }
    if(v3=="Answer 3"){
            score++;
    }
    
    if (score == 3) {
        alert("you got all " +score + " correct, move on");
        window.location.href = 'https://google.co.uk';
    } 
    else {
        alert("Incorrect, try again!");
    }
    
    
  }
</script>


</html>
Advertisement