AngularJs - Show the response only upon verifying the correct answer

Let me provide an overview of what has been implemented so far: When a user selects an answer in radio buttons and clicks on "Check Answer", the system displays either "Correct" (in green) or "Incorrect" (in red) in the first answer field. Additionally, the actual correct answer is shown in the "Solution" field (in green). However, there is an issue where the Solution field is displayed even when the answer is incorrect.

To see a sample of this implementation, please follow this link: https://codepen.io/anon/pen/PRoLXo

    <div data-ng-app="epubApp">
<div data-ng-controller="checkBoxFillinCtrl" data-ng-init="checkBoxData='p50';fillinBlankData='p50';">
<div class="quiz" id="quiz_1">
    <div class="question">
        <h4>1. A 6 m ladder of 20 kg rests with upper end on a smooth wall and lower end on a rough horizontal ground as shown below. Determine the minimum coefficient of friction so that the ladder does not slip?</h4><p class="qimage"><img src="../images/22.png" alt="images"/></p>
    </div>
    <div class="quiz-object multiple-choice">
        <div class="acontainer" style="margin:0em 1px 2px 1px;border:0px solid;">

                 <div id="check_box_table" >
            <table id="q_table" class="f1" data-ng-class="{'check_box_disabled':inputDisabled}">
                <tbody >

                    <tr>

                        <td  style="border:0px solid black;"><span class="check_box cElement"  data-check-box="cb[0]" data-quest-index="0"  data-check-index="0"></span></td>
                        <td >0.14</td>
                        </tr>
                        <tr>
                        <td  style="border:0px solid black;"><span class="check_box cElement" data-check-box="cb[0]" data-quest-index="0"  data-check-index="1"></span></td>
                        <td >0.29</td>
                        </tr>
                        <tr>
                        <td  style="border:0px solid black;"><span class="check_box cElement" data-check-box="cb[0]" data-quest-index="0"  data-check-index="2"></span></td>
                        <td >0.19</td>
                        </tr>
                        <tr>
                        <td  style="border:0px solid black;"><span class="check_box cElement" data-check-box="cb[0]" data-quest-index="0"  data-check-index="3"></span></td>
                        <td >0.35</td>
                        </tr>




                </tbody>
            </table>
        </div>
            <div id="correct1" style="border:1px solid gray;border-radius:5px;color:#616360;background-color:#F3F3F3;margin:1em 0em 2em 1em;font-size:100%;padding:10px;width:80%;">
                <b>Correct or Incorrect?</b>
                <!-- Replace each correct text in the below paragraphs -->
                <td><span class="result" data-ng-class="cb[0].resultClass"></span></td>
            </div>
            <div id="feedback1" style="border:1px solid gray;border-radius:5px;color:#616360;background-color:#F3F3F3;margin:0em 0em 2em 1em;font-size:100%;padding:10px;width:80%;">
                <b>Solution</b>
                <!-- Replace each feedback in the below paragraphs -->
                <p class="feedback-text">

                </p>
                <p data-ng-show="answerVisible" class="feedback-text">
Consider the FBD of the ladder<br/>
 <br/>
A = Normal reaction at lower end<br/>
B = Normal reaction at upper end<br/>
f = frictional force acting at horizontal surface<br/>
W = weight of ladder = 20 * 10 = 200 N<br/>
Considering horizontal and vertical equilibrium<br/>
f = B<br/>
A = W <br/>
So A = 200 N<br/>
Taking moment about lower end<br/>
B * 6 * sin 60&#176; - W * 6/2 * cos 60&#176; = 0<br/>
B * 6 * &#8730;3 /2 = 200 * 3 * &#189; = 300<br/>
B * 3 * &#8730;3 = 300<br/>
B = 100/&#8730;3 = 57.74 N<br/>
f = &#181; * N = B<br/>
&#181; = coefficient of friction <br/>
N = normal reaction = A = W = 200 N<br/>
f = &#181; * 200 = 57.74<br/>
&#181; = 57.74/200 = 0.29


                </p>
                <p class="feedback-text">
                </p>
                <p class="feedback-text">

                </p>
            </div>
        </div>
    </div>
    <div class="submitcontainer">
        <p style="text-align:left;">
            <div class="submit1" style="z-index:2;">
            <button class="resetBtn check"  style="font-family: Arial, Helvetica, sans-serif;font-weight: bold;color:white;background-color:#616360;font-size:100%;padding:5px;margin-top:1em;margin-right:1em;"  data-ng-show="resetVisible" data-ng-click="onReset()">RESET</button>
            <button class="submitBtn reset" id="reset_1"  style="font-family: Arial, Helvetica, sans-serif;font-weight: bold;color:white;background-color:#616360;font-size:100%;padding:5px;margin-top:1em;margin-right:1em;"   data-ng-show="submitVisible" data-ng-click="onSubmit()">Check Answer</button>


        </div>
        </p>
    </div>

    </div>

</div>
</div>

Any insights or samples you can provide would be greatly appreciated. Thank you for your help.

Answer №1

The main problem lies in the line of code $scope.answerVisible = true;.

To address this issue, you should eliminate $scope.answerVisible = true; from the submit function as it causes the div to become visible each time the Check Answer button is clicked.

To rectify this, I have repositioned the code properly.

Within the validate function, the answer is validated and based on correctness, the value of $scope.answerVisible is set to either true or false.

Below is the updated function:

 function validate() {
  allCorrect = true;
  data.forEach(function (val, index) {
  $scope.cb[index].clickable = false;
  $scope.cb[index].showClass = [];
  var groupCheckCorrect = $scope.cb[index].checked.length ? true : false;
  if (Array.isArray(val)) {
    $scope.cb[index].checked.forEach(function (v, i) {
      if (v) {
        if (val.indexOf(i) > -1) {
          $scope.answerVisible =  true;                   
          $scope.cb[index].showClass[i] = 'correct';
        } else {
          $scope.cb[index].showClass[i] = 'wrong';
          allCorrect = false;
          groupCheckCorrect = false;
        }
      }
    });
  } else {
    $scope.cb[index].checked.forEach(function (v, i) {
      if (v) {
        if (val == i) {
          $scope.answerVisible =  true;                 
          $scope.cb[index].showClass[i] = 'correct';
        } else {
          $scope.cb[index].showClass[i] = 'wrong';
          allCorrect = false;
          groupCheckCorrect = false;
        }
      }
    });
  }

  $scope.cb[index].resultClass = groupCheckCorrect ? "all_correct" : "all_wrong";
});

/** for fill up */
$scope.inputDisabled = true;
angular.forEach(fillup_data, function (d, i) {
  if ($scope.fill[i] != undefined && d.toLowerCase() == $scope.fill[i].toLowerCase()) {
    $scope.fillResult[i] = fillup_correct;
  } else {
    $scope.fillResult[i] = fillup_wrong;
  }
});
user_fill_answer = [];
user_fillResult_answer = [];
angular.copy($scope.fill, user_fill_answer);
angular.copy($scope.fillResult, user_fillResult_answer);
/** */

}

Answer №2

To begin, I must emphasize the importance of using secure practices when it comes to storing sensitive information on the front end. It is crucial not to expose answers in a way that can easily be accessed and exploited by technically savvy users, as this can compromise the system's security.

Instead, consider making an API call to verify and validate the answer when there is a change in options. If the answer is correct, dynamically add a class using ng-class; if incorrect, handle it accordingly.

By following this approach, you can safeguard your correct answers from being exposed to users. If you encounter any challenges along the way, don't hesitate to seek assistance.

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

Display information using AngularJS within the Ionic framework

I am attempting to display a variable that is within a for loop. Here is my code where I store the value of $scope.datosTuto[i].Nombre in a variable. When I use an alert to print $scope.NombTuto, I can see the data but I want to display it on my HTML page. ...

Transmit an unmodifiable array using JSON and Ajax

Is there a way to transmit arrays in a non-editable format? The data I wish to transmit looks like this: var items = []; //console.log(JSON.stringify(items)); allitems = JSON.stringify(items); [{ "assetid": "7814010469", "classid": "1797256701", ...

What is the process for creating a parent container in which clicking anywhere inside will cause a child container (built with jQuery UI draggable) to immediately move to that location?

This is a rundown of tasks that I am struggling to code more effectively: When the bar is clicked anywhere, I want the black dot button to instantly move there and automatically update the displayed percentage below it. Additionally, when I drag the butt ...

Executing multiple functions with onPress in React Native

When I press onPress using TouchableOpacity, I am attempting to invoke multiple functions. Here's an example: functionOne(){ // perform an action } functionTwo(){ // execute something } <TouchableHighlight onPress{() => this.functionOne()}/& ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

React application no longer displaying content following the upgrade to React 18 version

My React App was functioning perfectly, but after updating to React 18, MUI v5, and Redux v5, it stopped rendering anything. When I check the terminal, it shows: "webpack compiled successfully" However, in the Chrome console, I see: Warning: In ...

Updating the regex pattern for the date format to dd-M-yy in jQuery Validation Engine

Snippet for validating date format using JavaScript: "date": { // Custom function to check if date is valid with leap year consideration "func": function (field) { //var pattern = ne ...

What is the correct way to declare a new variable for a JSON object?

Within my Node JS application, I have an endpoint where I am attempting to retrieve data from two separate mongo collections. However, when trying to combine this data, I am encountering difficulties adding a new property to the JSON object. const getLesso ...

Using either Javascript or jQuery, I want to set a value within an if statement

Can I set a value within an if statement, like this: if (a = jQuery("#user > .mask.fix > .a1").css('display') != 'none'){ b = a + 'hello'; //b=jQuery("#user > .mask.fix > .a1").css('display')+&apos ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

What is the best way to connect a directive's attribute to a dropdown menu in Angular.js?

Within a dropdown, I have a selection of templates that are connected to $scope.templates: [{"id":1, "name":"Test 1",{"id":2, "name":"Test 2"}]. Furthermore, there is a directive in place, <editor data-template="1"></editor> The goal is to ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...

Modifying React routes does not alter the path or outlet of the routes

On the app.js file, I have the following routes: import React from "react"; import Login from "./pages/Login"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Dashboard from "./pages/Dashboard" ...

The form is functioning properly on mobile devices but is currently experiencing issues on the server

Everything runs smoothly when accessing the website and using the form on localhost. However, once it's uploaded to a server, the form only functions correctly on desktop devices. On mobile, the form fails to filter and displays all professionals inst ...

Disabling an anchor using the 'disabled' property is proving to be a challenge for me

I'm attempting to dynamically enable or disable an anchor element based on the user's role. So far, I've tried a few different methods: document.getElementById('myBtn').disabled = true; However, this returns an error: The propert ...

Can you explain the concept of Cross-origin requests?

My JavaScript application is designed to detect single, double right, and double left clicks. A single click triggers an asynchronous request to the HTTP server, while the rest are intended to change the user interface on the client side. However, I am str ...

Passing data into an Angular-UI modal component

My goal is to pass model data into a modal window when it is opened. Essentially, I want the modal window to display detailed information based on what element the user clicks on. I have actually created a working example using Plunker, but I am strugglin ...

Find and replace string words containing special characters such as $ or !

Looking to process an input string in a specific way - // Input string - 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$' // Processed string 'My pen cost is <penCost> manufactured ...