Home » Jquery » javascript – I have a jQuery quiz that works but it hides the wrong answers to the previous questions once an a correct answer is made

javascript – I have a jQuery quiz that works but it hides the wrong answers to the previous questions once an a correct answer is made

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a quiz that works but it hides the wrong answers to the previous questions once an a correct answer is made. I want the 6 question results to appear even if some of them are incorrect. I hate to repeat the same code 6 times.

https://designaire.com/test1/health.html

<script>
    $(function() {
          $('.exp').hide();
          $('.wrong').hide();
          $('input[name="test"]').on('click', function() {
            var el = $(this);
            if (el.val() == 'ans') {
              el.parents('.q').nextAll('.exp').first().show();
              el.parents('.q').nextAll('.wrong').first().hide();
              $('.wrong').hide();
            } else {
              el.parents('.q').nextAll('.wrong').first().show();
              el.parents('.q').nextAll('.exp').first().hide();
            }
          })
        });
    </script>
    <form class="q">
    1. Janelle is excitedly telling her friend Reina how her job interview went. Reina keeps texting her boyfriend.
      <div class="answer">
    <input name="test" type="radio" value="inc" />
    Respect
    <input name="test" type="radio" value="ans" />
    Disrespect
    </div>
    </form>
    <div class="exp">★ Good Job!</div>
    <div class="wrong">Take another look at the examples in this lesson.</div></div>
How to&Answer:

You have a condition which hides all the elements with the wrong answers, just get rid of it.

<script>
    $(function() {
          $('.exp').hide();
          $('.wrong').hide();
          $('input[name="test"]').on('click', function() {
            var el = $(this);
            if (el.val() == 'ans') {
              el.parents('.q').nextAll('.exp').first().show();
              el.parents('.q').nextAll('.wrong').first().hide();
              $('.wrong').hide(); // => remove this line
            } else {
              el.parents('.q').nextAll('.wrong').first().show();
              el.parents('.q').nextAll('.exp').first().hide();
            }
          })
        });
    </script>

Example : https://jsfiddle.net/L0u798by/