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

Retrieving and storing successful response data in Angular JS using the $http service caching

My dataFactory is set up to retrieve posts in a simple manner: dataFactory.getPosts = function () { if (this.httpPostsData == null) { this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page ...

What is the best way to wait for a series of subscriptions to complete?

I am currently facing challenges with Observables while working on a complex REST API query function that involves intricate logic and multiple requests and responses. Although I have already written numerous functions with subscriptions like the ones bel ...

Tips for troubleshooting Node.js React Express applications

Having a background in traditional programming, I am used to putting breakpoints in code and having the debugger take me directly to the problematic section when executed. However, as I delve into web app development, it seems that debugging is limited to ...

Troubleshooting problem with JSON decoding in PHP and json_encode

Encountering an issue when parsing JSON received from a PHP backend. In my PHP code, I have an array that I send using json_encode: $result[] = (object) array('src' => "{$mergedFile}", 'thumb_src' => "{$thumb_file}"); echo json_e ...

Using the Spread Operator to modify a property within an array results in an object being returned instead of

I am trying to modify the property of an object similar to this, which is a simplified version with only a few properties: state = { pivotComuns: [ { id: 1, enabled : true }, { id: 2, enabled : true ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

leveraging jQuery mobile for asynchronous requests

I've been attempting to print a jQuery mobile element using ajax, but I'm running into an issue where the result isn't being encoded as jQuery mobile is intended to do. Below is a simplified excerpt of the JavaScript code responsible for t ...

Odd behavior of the "for in" loop in Node.js

It seems like I'm struggling with the use of the "for in" statement. When working with a JSON document retrieved from a mongodb query (using nodejs + mongoose), its structure looks something like this: [{ "_id":"596f2f2ffbf8ab12bc8e5ee7", "da ...

After a single click, the functionality of jquery.nav.js seems to be malfunctioning

Encountering an error message: Uncaught TypeError: Cannot read property 'top' of undefined(…) jquery.nav.js:183 In an effort to convert my web app into a Single Page Application (SPA) using the jquery.nav.js library (available at https://githu ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

Issue with the execution of Javascript code. Edit required

After creating a registration form that allows users to input their information for registration, I encountered an issue where if certain fields were left empty or if the user name was unavailable or the email address was already registered, a warning mess ...

What is the best method for loading multiple HTML files into a Div container?

Recently, I made the decision to improve the look of an online manual I have been working on for my company by incorporating Bootstrap. The manual is structured with a tree-view that contains titles linking to HTML files with information and CSS stylesheet ...

Upon attempting to start the server, the module 'express-stormpath' could not be located

Upon trying to execute node server.js (in a regular terminal without superuser or root permissions), the following error is thrown: alphaunlimitedg@AUNs-PC:~/my-webapp$ node server.js module.js:442 throw err; ^ Error: Cannot find module 'expr ...

An old-school Ajax request abruptly interrupted halfway through

function submitLogin(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; var testlabel = document.getElementById('testlabel').value; ...

Upon reviewing the webpage using an IPAD and AngularJS

I recently completed a web application using AngularJS and PHP. It functions smoothly on Chrome and Firefox, but it encounters loading issues on IE due to the number of JS files. To solve this problem, I will need to reduce the amount of JS files for it to ...

Different ways to provide user feedback on a SPA website following AJAX requests

I have a single-page application website developed using React.js. What are some options for notifying the user of successful/failed/pending AJAX calls resulting from various user interactions? I am aware of Toastr-style messages that appear in the corner ...

Updating a Nested Form to Modify an Object

There is an API that fetches an object with the following structure: { "objectAttributes": [ { "id": "1", "Name": "First", "Comment": "First" }, { "id": "2", "Name": "Second", "Comment": "Second" } ] ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...