Yamada Akira
Yamada Akira

Reputation: 87

How to know which radio buttons are checked and redirect them correctly

I'm doing a quiz for a company where users answer three questions and if they are all correct they should get redirected to a page where they fill in their contact information for a chance at winning a prize. If one or more questions are answered wrong they should get redirected to another page.

I need to mark the correct answers and then check for them. If all questions are answered right: redirect to motivering.html If one or more questions are wrong: redirect to tyvarr.html

I have tried to check for the values and only come up with this. It's not correct and I'm almost certain it's not the most suitable way.

jQuery

$(document).ready(function() {
    $('#questions input').on('change', function() {
       console.log($('input[name=questionOne]:checked', '#questions').val());
       console.log($('input[name=questionTwo]:checked', '#questions').val());
       console.log($('input[name=questionThree]:checked', '#questions').val());
    });
});

My mark up - HTML

<form method="POST" id="questions">
    <div class="form-group" id="questionOne">
        <h3>Question 1</h3>
        <div class="radio">
            <input type="radio" name="questionOne" id="question1" class="radio" value="1" required/>
            <label for="question1">Option 1</label>
        </div>
        <div class="radio">
            <input type="radio" name="questionOne" id="question2" class="radio" value="2"/>
            <label for="question2">Option 2 - Right answer</label>
        </div>
        <div class="radio">
            <input type="radio" name="questionOne" id="question3" class="radio" value="3"/>
            <label for="question3">Option 3</label>
        </div>
    </div>

    <div class="form-group" id="questionTwo">
        <h3>Question 2</h3>
        <div class="radio">
            <input type="radio" name="questionTwo" id="question4" class="radio" value="4" required/>
            <label for="question4">Option 1</label>
        </div>
        <div class="radio">
            <input type="radio" name="questionTwo" id="question5" class="radio" value="5"/>
            <label for="question5">Option 2</label>
        </div>
        <div class="radio">
            <input type="radio" name="questionTwo" id="question6" class="radio" value="6"/>
            <label for="question6">Option 3 - Right answer</label>
        </div>
    </div>

    <div class="form-group" id="questionThree">
        <h3>Question 3</h3>
        <div class="radio">
            <input type="radio" name="questionThree" id="question7" class="radio" value="7" required/>
            <label for="question7">Option 1</label>
        </div>
        <div class="radio">
           <input type="radio" name="questionThree" id="question8" class="radio" value="8"/>
            <label for="question8">Option 2 - Right answer</label>
        </div>
        <div class="radio">
            <input type="radio" name="questionThree" id="question9" class="radio" value="9"/>
            <label for="question9">Option 3</label>
        </div>
    </div>

    <div class="buttons">
        <a href="index.html" class="btn btn-default form_button_cancel">Avbryt</a>
        <button type="submit" class="btn btn-default form_button_next">Nästa</button>
    </div>
</form>

My style - CSS

@charset "utf-8";
/* CSS Document */

/* FONT */
@import url('https://fonts.googleapis.com/css?family=Nunito:400,700');

body, textarea, input{
    font-family: 'Nunito', sans-serif;
    font-weight:400;
    font-size:16px;
    line-height:26px;
    letter-spacing:0.5px;
}
/*.start{
    background-color:tomato;
}*/
h1, h2, h3, .form_button_start, .form_button_cancel, .form_button_next{
    font-family: 'Nunito', sans-serif;
    font-weight:600;
}
h1, h2, h3{
    text-transform:uppercase;
}
h3{
    font-size:21px;
    margin-top:50px;
}
textarea{
    resize:none;
}
ul{
    list-style:none;
}

.radio label {
  width: 100%;
  border-radius: 3px;
  border: 1px solid #D1D3D4
}
/* hide input */
input.radio:empty {
    margin-left: -999px;
}
/* style label */
input.radio:empty ~ label {
    position: relative;
    line-height: 3.5em;
    text-indent: 2em;
    margin-top: 1em;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    font-size:16px;
    text-transform:uppercase;
}
input.radio:empty ~ label:before {
    position: absolute;
    display: block;
    top: 0;
    bottom: 0;
    left: 0;
    content: '';
    width: 2.5em;
    background: #D1D3D4;
    border-radius: 3px 0 0 3px;
}
/* toggle hover */
input.radio:hover:not(:checked) ~ label:before {
    /*content:'\2714';*/
    text-indent: .9em;
    color: #C2C2C2;
}
input.radio:hover:not(:checked) ~ label {
    color: #888;
}
/* toggle on */
input.radio:checked ~ label:before {
    /*content:'\2714';*/
    text-indent: .9em;
    color: #9CE2AE;
    background-color: #4DCB6D;
}
input.radio:checked ~ label {
    color: #333;
}
/* radio focus */
input.radio:focus ~ label:before {
    box-shadow: 0 0 0 3px #999;
}

/* Butto style */
.form_button_cancel, .form_button_next, .form_button_start{
    width: 200px;
    text-transform: uppercase;
    line-height: 30px;
    margin: 20px 0;
}
.form_button_start{
    background-color:green;
    border:0px solid transparent;
}
.form_button_next{
    background-color: green;
    float:right;
    border:0px solid transparent;
}
.form_button_cancel{
    float:left;
}

Upvotes: 0

Views: 55

Answers (1)

Mr_KoKa
Mr_KoKa

Reputation: 618

$(document).ready(function() {
    $('#questions input').on('change', function() {
      /* Answers array, if there are more questiones I would think about changing questionOne to question1
       * and build this array in a loop getting values by something like:
       *   userAnswers.push($('input[name=question'+ i +']:checked', '#questions).val());
       * or even group them under one class and query for .question:checked
       */
      var userAnswers = [
        $('input[name=questionOne]:checked', '#questions').val(),
        $('input[name=questionTwo]:checked', '#questions').val(),
        $('input[name=questionThree]:checked', '#questions').val()
      ];
      
      //Array that contains right answers, indexes must match userAnswers array.
      var rightAnswers = [2, 6, 8];
      
      //Check if all answers are defined
      for(var i = 0; i < userAnswers.length; i++){
        if(typeof userAnswers[i] === 'undefined'){
          return;
        }
      }
      
      //Check if all answers are rightAnswers
      for(var i = 0; i < userAnswers.length; i++){
        if(userAnswers[i] != rightAnswers[i]){
          return console.log('Found wrong answer!');
        }
      }
      
      console.log('All answers are correct.');
    });
});
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>repl.it</title>
        <link href="index.css" rel="stylesheet" type="text/css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
      <form method="POST" id="questions">
        <div class="form-group" id="questionOne">
            <h3>Question 1</h3>
            <div class="radio">
                <input type="radio" name="questionOne" id="question1" class="radio" value="1" required/>
                <label for="question1">Option 1</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionOne" id="question2" class="radio" value="2"/>
                <label for="question2">Option 2 - Right answer</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionOne" id="question3" class="radio" value="3"/>
                <label for="question3">Option 3</label>
            </div>
        </div>
    
        <div class="form-group" id="questionTwo">
            <h3>Question 2</h3>
            <div class="radio">
                <input type="radio" name="questionTwo" id="question4" class="radio" value="4" required/>
                <label for="question4">Option 1</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionTwo" id="question5" class="radio" value="5"/>
                <label for="question5">Option 2</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionTwo" id="question6" class="radio" value="6"/>
                <label for="question6">Option 3 - Right answer</label>
            </div>
        </div>
    
        <div class="form-group" id="questionThree">
            <h3>Question 3</h3>
            <div class="radio">
                <input type="radio" name="questionThree" id="question7" class="radio" value="7" required/>
                <label for="question7">Option 1</label>
            </div>
            <div class="radio">
               <input type="radio" name="questionThree" id="question8" class="radio" value="8"/>
                <label for="question8">Option 2 - Right answer</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionThree" id="question9" class="radio" value="9"/>
                <label for="question9">Option 3</label>
            </div>
        </div>
    
        <div class="buttons">
            <a href="index.html" class="btn btn-default form_button_cancel">Avbryt</a>
            <button type="submit" class="btn btn-default form_button_next">Nästa</button>
        </div>
    </form>
    </body>
</html>

And for redirect instead of printing 'Found wrong answer!' or 'All answers are correct!' in console, you would do:

  //Check if all answers are rightAnswers
  for(var i = 0; i < userAnswers.length; i++){
    if(userAnswers[i] != rightAnswers[i]){
      window.location.href = 'wrong.html';
      return; // End here, and do not execute further redirection.
    }
  }

  window.location.href = 'right.html';

That return inside loop makes sure that script will end function execution there, and it will not execute 'right.html' redirection.

These two loops, to check if answers are defined, and if they're correct could be merged into one, but with some more code that will note that all were defined.

Edit: To answer your question in comment bellow, at first I thought I will bind it to button onclick event, but to keep validation that is handy in this case (when some questions aren't answered it notices the user about it) I think form's onsubmit will be better. I still prevent the default behavior so the form isn't really submitted, but keep in mind if someone will have js disabled, it will submit the form so keep that in mind. So, the next button is submit type, and it will attempt to submit form, in onsubmit event handler I prevent form submition and I check answers.

$(document).ready(function() {
    $('#questions').on('submit', function(e) {
      e.preventDefault(); // Prevent form submition; 
      
      var userAnswers = [
        $('input[name=questionOne]:checked', '#questions').val(),
        $('input[name=questionTwo]:checked', '#questions').val(),
        $('input[name=questionThree]:checked', '#questions').val()
      ];
      
      //Array that contains right answers, indexes must match userAnswers array.
      var rightAnswers = [2, 6, 8];
      
      //Check if all answers are defined
      for(var i = 0; i < userAnswers.length; i++){
        if(typeof userAnswers[i] === 'undefined'){
          return;
        }
      }
      
      //Check if all answers are rightAnswers
      for(var i = 0; i < userAnswers.length; i++){
        if(userAnswers[i] != rightAnswers[i]){
          return console.log('Found wrong answer!');
        }
      }
      
      console.log('All answers are correct.');
    });
});
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>repl.it</title>
        <link href="index.css" rel="stylesheet" type="text/css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
      <form method="POST" id="questions">
        <div class="form-group" id="questionOne">
            <h3>Question 1</h3>
            <div class="radio">
                <input type="radio" name="questionOne" id="question1" class="radio" value="1" required/>
                <label for="question1">Option 1</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionOne" id="question2" class="radio" value="2"/>
                <label for="question2">Option 2 - Right answer</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionOne" id="question3" class="radio" value="3"/>
                <label for="question3">Option 3</label>
            </div>
        </div>
    
        <div class="form-group" id="questionTwo">
            <h3>Question 2</h3>
            <div class="radio">
                <input type="radio" name="questionTwo" id="question4" class="radio" value="4" required/>
                <label for="question4">Option 1</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionTwo" id="question5" class="radio" value="5"/>
                <label for="question5">Option 2</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionTwo" id="question6" class="radio" value="6"/>
                <label for="question6">Option 3 - Right answer</label>
            </div>
        </div>
    
        <div class="form-group" id="questionThree">
            <h3>Question 3</h3>
            <div class="radio">
                <input type="radio" name="questionThree" id="question7" class="radio" value="7" required/>
                <label for="question7">Option 1</label>
            </div>
            <div class="radio">
               <input type="radio" name="questionThree" id="question8" class="radio" value="8"/>
                <label for="question8">Option 2 - Right answer</label>
            </div>
            <div class="radio">
                <input type="radio" name="questionThree" id="question9" class="radio" value="9"/>
                <label for="question9">Option 3</label>
            </div>
        </div>
    
        <div class="buttons">
            <a href="index.html" class="btn btn-default form_button_cancel">Avbryt</a>
            <button type="submit" class="btn btn-default form_button_next">Nästa</button>
        </div>
    </form>
    </body>
</html>

Upvotes: 1

Related Questions