Highlighted Answer: Choosing between two options in the quiz

I am currently developing an employability quiz for my university project. Each question offers a choice between Yes and No answers.

If the user selects the Yes answer, it will be highlighted in green and display the correct answer below.

However, if the user selects the No answer, it gets highlighted in red while also incorrectly highlighting the Yes answer box in green even though it hasn't been selected.

This code snippet showcases Question 1's HTML structure:

    $(document).ready(function() {
      //get total number of questions
      var $questionNumber = $('h2').length;
      console.log($questionNumber);
      //caching final score
      var $totalScore = 0;

      $('li').click(function() {
        //caching variables
        var $parent = $(this).parent();
        var $span = $(this).find('.fa');

        //deactivate options on click
        $parent.find('li').off("click");

        //check for .correct class
        //if yes
        if ($(this).hasClass('correct')) {
          //add .correctAnswer class
          $(this).addClass('correctAnswer');
          //find next span and change icon
          $span.removeClass('fa fa-square-o').addClass('fa fa-check-square-o');
          //reduce opacity of siblings
          $(this).siblings().addClass('fade');
          //show answer
          var $answerReveal = $parent.next('.answerReveal').show();
          var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
          var $toShowFalse = $answerReveal.find('.quizzAnswerF');
          $toShowCorrect.show();
          $toShowFalse.remove();
          //add 1 to total score
          $totalScore += 1;
          //console.log($totalScore);
        } else {
          //add .wrongAnswer class
          $(this).addClass('wrongAnswer').addClass('fade');
          //change icon
          $span.removeClass('fa fa-square-o').addClass('fa fa-check-square-o');
          //reduce opacity of its siblings
          $(this).siblings().addClass('fade');
          //show wrong Message
          var $answerReveal = $parent.next('.answerReveal').show();
          var $toShowCorrect = $answerReveal.find('.quizzAnswerC');
          var $toShowFalse = $answerReveal.find('.quizzAnswerF');
          $toShowCorrect.remove();
          $toShowFalse.show();
          //locate correct answer and highlight
          $parent.find('.correct').addClass('correctAnswer');
        };
      }); //end click function

      //print Results
      function printResult() {
        var resultText = '<p>';
        if ($totalScore === $questionNumber) {
          resultText += 'You got ' + $totalScore + ' out...';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>1. I know where/how to find out about work experience, internship and placement opportunities</h2>
<ul class="simpleList">
  <li class="simpleListAnswer correct">
    <span class="fa fa-square-o"></span>
    <span class="simpleListText">Yes I know where to look.</span>
  </li>

  <li class="simpleListAnswer">
    <span class="fa fa-square-o"></span>
    <span class="simpleListText">No I'm not sure.</span>
  </li>
</ul>
<!--end simpleList-->

<div class="answerReveal">

  <div class="quizzAnswerC">
    <div class="answerHeader">
      <h3 class="correctMessage"><i class="fa fa-check-circle "></i>Awesome!</h3>
    </div>
    <div class="answerText">
      <p id="bravo">Well done!</p>
    </div>
  </div>
  <div class="quizzAnswerF">
    <div class="answerText">
      <p id="sorry">You can find more information on this in Room 014</p>
    </div>
  </div>
</div>

If anyone could offer assistance on resolving this issue of incorrect double-selection, your help would be highly appreciated as I am unable to identify the root cause!

Answer №1

Please consider removing the following line:

$parent.find('.correct').addClass('correctAnswer');

This line is highlighting the correct answer in your jQuery code, which might not be necessary.

Check out this jsFiddle example for reference

Answer №2

Great code! Thank you!


I'm looking to incorporate an answer reset function into this script without having to reload the page. Any ideas?

Here's an example using a Scroll To Top script:

<a href="#" title="Scroll UP" class="scrollup">Scroll UP</a>
<script type="text/javascript">
    $(document).ready(function() {

        $(window).scroll(function() {
            if ($(this).scrollTop() > 100) {
                $('.scrollup').fadeIn();
            } else {
                $('.scrollup').fadeOut();
            }
        });

        $('.scrollup').click(function() {
            $("html, body").animate({
                scrollTop: 0
            }, 600);
            return false;
        });

    });
</script>

If possible, I also need to implement an "Answer reset" function for when the Up script is clicked.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rephrasing links with JavaScript, excluding links leading to a particular directory

I am facing an issue with my webpage where I need to rewrite links using Javascript. Specifically, all the links within the div id="container" need to be changed from "post=post-number-234" to "?id=blog&post=post-number-234". Currently, I have a scrip ...

Retrieve the DOM node representing a dropdown menu

I'm struggling with retrieving the selected value from a drop-down list that is used to set parameters for a query sent to the back end. Once the user selects the desired options from the drop-down, they click a button that triggers a call to the bac ...

Choosing specific information in Typescript response

I am encountering an issue with my HTML where it displays undefined(undefined). I have checked the data in the debugger and I suspect that there may be an error in how I am using the select data. Here is a snippet of the code: <div *ngIf="publishIt ...

Initialize a jQuery UI resizable element by selecting a specific element that has been dynamically added to the DOM

Is there a way to start a jquery ui resizable instance using a selector added to the DOM by jquery itself? Here is a snippet of the script I am currently working with: HTML: <div class='lyr'></div> jQuery: // Add class $('lyr ...

UIBootstrap Tooltip Triggering on Various Events

Can the triggers for Tooltip in UIBootstrap be extended to accept multiple conditions? For instance, I would like my tooltip to close on both 'blur' and 'click' actions. I attempted to pass in an array but it did not work: $tooltipPr ...

code snippet in ckeditor submission eliminating the use of specific color combinations

Currently, I am integrating a blog writing feature into my website. To achieve this, I have utilized ckeditor along with the ckeditor code snippet plugin for proper formatting of the code snippets. Everything seems to be functioning correctly while I' ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Disable blur effect on child element with relative positioning

Is there a way to create a background blur effect using material cards without affecting a specific div? <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://code.getmdl.io/ ...

Adding information to a MySQL database using JavaScript and invoking a PHP script

I'm currently facing an issue with my code that involves calling a .php file to insert data into a MySQL database. However, I am unable to get the .php file to run successfully. Can anyone provide some suggestions? As someone who is new to scripting, ...

When utilizing ElevateZoom, the zoom function consistently appears positioned behind the main image

I am facing an issue with the zoom functionality while using the elevate zoom plugin. The problem occurs when I have a container div that holds all the content, a mainDiv with a background image, and a separate div toZoom. The issue is that the zoom lens ...

The CSS menu dropdown fails to function properly on desktop view when there is longer content present

I attempted to merge two different navigation bars, one sticky and the other responsive. The goal was to combine https://www.w3schools.com/howto/howto_js_navbar_sticky.asp with https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp Curr ...

Changing Image to Different File Type Using Angular

In my Angular Typescript project, I am currently working on modifying a method that uploads an image using the input element of type file. However, I no longer have an input element and instead have the image file stored in the assets folder of the project ...

Ways to showcase title using ng-repeat

<input type="text" ng-model= "name" title="{{name}}">//this title displays the name that is contained in ng-model Similarly... <select title ="{{item.actionId}}" ng-model="item.actionId"> <option ng-repeat="action in actionList" value="{{ ...

Modify the width of the progress bar in Bootstrap using AngularJS

I'm new to AngularJS and I'm attempting to dynamically update the width of a progress bar based on changes in my controller. Here is what I currently have: <span id="percentage">$ {{getTotal()}} ({{getPercentage()}}%)</span> <div ...

Attempting to change the checked state of a child component from the parent component in a synchronous manner

Please run the demo provided below: let myCheckbox = Vue.component('my-checkbox', { template: `<div> <input type="checkbox" id="check1" :checked="checked" @change="change">{{checked}} </ ...

Managing Data Types in AJAX Requests

Can you help me figure out why my AJAX call is not reaching success after hours of troubleshooting? It seems like the issue lies in the dataType that the AJAX call is expecting or receiving (JavaScript vs JSON). Unfortunately, I'm not sure how to addr ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

Execute the PHP file using a script tag

Is there a way to include PHP code within <script>? For example, like this: `<script src="example.php">. I understand that the script tag is typically used for JavaScript, but I want PHP to generate JS that can be inserted using the s ...

methods for retrieving data from a Laravel controller within an imported JavaScript file

My current approach involves using ajax to update a table based on the user's input. $('#user').change(function(){ var user= $("#user").val(); if (user !='None'){ $.ajax({ type: "GET", url: '/getUserAccounts/&a ...

Securing data in the browser using JavaScript encryption and decrypting on the server side using Node.js

After hours of trying to encrypt a message using AES256 in the browser, send it to the server, and then decrypt it, I keep encountering this server-side error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt Despite using crypto- ...