Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz.

The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always show up as incorrect even when the answer is right. Through console.log, I discovered that although the input value changes, AngularJS does not recognize it. It keeps holding onto the initial value I entered in the quiz.

Plunkr Demo

HTML

<div id="myQuiz" ng-controller="QuizController">
    <h1>Test Your Knowledge:<span>Saturn</span></h1>
    <div class="progress">  
        <div class="{{ ($index === activeQuestion) ? 'on' : 'off' }} 
            {{ (myQuestion.questionState === 'answered') ? 'answered' : 'unanswered' }}
            {{ (myQuestion.correctness === 'correct') ? 'correct' : 'incorrect' }}" 
            ng-repeat="myQuestion in myQuestions">
        </div>
    </div>

    <div class="intro {{ (activeQuestion > -1) ? 'inactive' : 'active' }}"> 
        <h2>Welcome</h2>
        <p>Click to begin to test your knowledge of Saturn.</p>
        <p class="btn" ng-click="activeQuestion = 0">Begin</p>
    </div>

    <div class="question
        {{ $index === activeQuestion ? 'active' : 'inactive' }}
        {{ myQuestion.questionState === 'answered' ? 'answered' : 'unanswered' }}" 
        ng-repeat="myQuestion in myQuestions">
        <p class="txt"> {{ myQuestion.instructions }} </p>
        <div class="txt" ng-bind-html="myQuestion.question | trustAsHtml">
        </div>  

        <p class="ans" 
            ng-class="{  
                correct:isCorrect($index, $index)}"
            ng-click="checkAnswer($index, $index)">Check Answer 
        </p>

        <div class="feedback">
            <p ng-show="myQuestion.correctness === 'correct'"><strong>Correct</strong>.</p>
            <p ng-show="myQuestion.correctness === 'incorrect'">Oops! That is not correct.</p>
            <p> {{ myQuestion.feedback }} </p>
            <div class="btn" ng-click="selectContinue()">Continue</div>
        </div>
</div>

App.js

    (function(){
    var codeApp = angular.module('codeApp', ['ngSanitize']);

    codeApp.controller('QuizController', ['$scope', '$http', "$sce", function($scope, $http, $sce){
        $scope.score = 0;
        $scope.activeQuestion = -1;
        $scope.activeQuestionAnswered = 0;
        $scope.percentage = 0;

        $http.get('quiz_data.json').then(function(quizData){
            $scope.myQuestions = quizData.data;
            $scope.totalQuestions = $scope.myQuestions.length;
        });
        $scope.checkAnswer = function(qIndex,aIndex){
            var questionState = $scope.myQuestions[qIndex].questionState;

                if(questionState != 'answered') {
                    var userAnswer = document.getElementsByClassName("fillin")[0].value;
                    var correctAnswer = $scope.myQuestions[qIndex].questionAnswer;

                    $scope.myQuestions[qIndex].questionAnswer = correctAnswer;

                            if(userAnswer === correctAnswer){
                                $scope.myQuestions[qIndex].correctness = 'correct';
                                $scope.score += 1;
                                console.log('Correct!' + $scope.score);
                            }
                            else{
                                $scope.myQuestions[qIndex].correctness = 'incorrect';
                                console.log('Wrong!');
                                console.log(correctAnswer);
                                console.log(userAnswer);
                                console.log( document.getElementsByClassName("fillin")[0].value );
                            }
                        $scope.myQuestions[qIndex].questionState = 'answered';

                }else{
                    console.log('Something is wrong');
                }

        }

        $scope.selectContinue = function(){
            return $scope.activeQuestion += 1;

        }

        $scope.createShareLinks = function(percentage){

            var url = 'http://codifydesign.com';
            var emailLink = '<input type="text" placeholder="hi" /><a class="btn email" href="mailto:?subject=Try to beat my quiz score!&amp;body=I scored a '+percentage+'% on this quiz about Saturn. Try to beat my score at '+url+'">Email a friend</a>';
            var twitterLink = '<a class="btn twitter" target="_blank" href="http://twitter.com/share?text=I scored a '+percentage+'% on this quiz about Saturn. Try to beat my score at&amp;hashtags=SaturnQuiz&amp;url='+url+'">Tweet your score</a>';
            var newMarkup = emailLink + twitterLink;
            return $sce.trustAsHtml(newMarkup);
        }
    }]).filter('trustAsHtml', [
    '$sce',
    function($sce) {
        return function(value) {
            return $sce.trustAsHtml(value);
        }
    }
    ]);
})();

data.json

[
    {
        "questionId": 0,
        "question" : "Saturn is <input id='guess-input' class='fillin' ng-blur='clearValues()' type='text' name='\"six\"'> many planets from the sun?",
        "questionAnswer" : "six"
    },
    {
        "questionId": 1,
        "question" : "Around Saturn are <input id='guess-input' class='fillin' ng-blur='clearValues()' type='text' name='\"rings\"'>",
        "questionAnswer" : "rings"
    }
]

Answer №1

Your code is currently set to always search for the initial occurrence of an element with a specified class called fillin. Modify both occurrences of this...

document.getElementsByClassName("fillin")[0].value

...to the following...

document.getElementsByClassName("fillin")[aIndex].value

...and your code should start functioning correctly.

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

Discover the specific item within an array of objects

Anyone have information like this: const info = { Title : "Banana", Quantity : 10, Location : "Everywhere", Phone : 123456, A : 987, B : 654, } and there is another array of details as: const dataArr = ["Title",&q ...

Incorrect positioning on canvas

Is there a way to adjust text alignment within a canvas? Currently, my text is centered. However, when I change the text size, the alignment gets thrown off. Here is the code snippet: <canvas id="puzzle" width="480" height="480"></canvas> ...

JavaScript - Removing Content from an Element

I have a coding script that adds an image preview of uploaded images. The issue I am facing is that the previous image does not clear when the form is filled out again. The id of the div where thumbnail images are being displayed is "thumbnail". Can someo ...

How can I add an object to an array of objects in Vue.js?

Hey there! I'm new to Vue and currently working on understanding the whole concept of Vue and how to use it. Right now, my focus is on learning lists. JS: Vue.config.productionTip = false; new Vue({ el: '#app', data: { items: [ ...

Uniquely combining multiple jQuery appendTo functions into a single call

Is it possible to optimize this code snippet: jQuery('<img />',{alt:"Logo",src:"img/logo.jpg"}).appendTo("#scrittacentro"); jQuery('<h1 />',{text:'THE LCARS COMPUTER NETWORK',class:'cLightOrange lcars'}) ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

An AngularJS Dilemma: Troubleshooting JSON Integration

I am working with a JSON source and trying to fetch results from it using a post request. Interestingly, when I use the POSTMAN extension in Chrome, everything works perfectly fine. However, when I try the same thing with AngularJS, the page keeps loading ...

Discovering the keycode for the GO button in JavascriptDiscovering the keycode

Can anyone help me figure out how to find the keycode for the GO button using Javascript in an Android browser? ...

"Enhance Your Video Experience with a Personalized Play Button

Is it possible to customize the play icon for an embedded YouTube video? I came across a post discussing this topic: Can I change the play icon of embedded youtube videos? However, when trying to use something transparent as the new play button, the origin ...

Body Parser causing unexpected output

Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error: express_1 | TypeError: Cannot read property ' ...

Verifying the presence of an ID within a jquery cookie

I encountered an issue with this code on a product page. Whenever I click the save button, it stores the product ID in a jQuery cookie. The IDs are stored in the cookie like this: 1,2,3,4... If an ID is already in the cookie, there seems to be a problem a ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

Transforming this JavaScript code to be less intrusive by implementing an event listener for an unidentified ID

As I work on enhancing the functionality of this user interface, I've encountered a challenge with two tabs that require a proper event listener to ensure my JavaScript functions smoothly. This obstacle has been hindering my progress, but as I delve i ...

Ways to adjust the color of a cell in a table

I am working on customizing a table in my website where I need to change the color of a single cell in each row, similar to the example shown in this image: Here is the HTML code that I have implemented so far: <table class="table table-hover t ...

Testing React JSX components using ES6 unit tests

Currently, I am utilizing React, JSX, ES6, and Karma. I am facing an issue with my code. Can anyone pinpoint what might be wrong? I am attempting to execute a test using Karma-Runner but encountering some obstacles: let React = require("react") ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

Achieving a perfect circle can be accomplished by setting both the width and height to the same

Trying to make the height of an element equal to its width For example, aiming for a perfect circle Although the console displays equal values, the resulting height is noticeably greater than the width $('button').on('click', funct ...

Struggling to employ JavaScript events when submitting a form to verify the fields

My goal is to create a form with fields that have real-time validation using JavaScript. I have achieved this by utilizing Java events in the following way: Text field onkeyup: This event sends a request to check for errors in the field every time a key ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...