Maintaining Radio Input Selection in Vue.js Mobile App Despite Rendering New Questions

Seeking an alternative method, I have devised a clever solution to display survey questions without utilizing v-for loop. The purpose of this approach in a mobile android app is to prevent all questions from being rendered simultaneously and causing excessive scrolling. While the logic functions correctly, there seems to be an issue where upon selecting an answer and rendering the next question, the radio input for selecting the answer does not reset, retaining the previously chosen option. This problem does not occur when using v-for to display the questions, which is not what I want.

<div class="container-fluid bg-light vh-100" v-if="isLoaded">
    <div class="row m-0">
    
      <div class="col-12 card shadow p-0 mt-5">
        <div class="card-header">
          <h6 class="fw-bold">{{ questions[n].question }}</h6>
        </div>
        <div class="card-body">
          <div class="form-check mb-3" v-for="(choice, index) in questions[n].choices" :key="index">
            <input class="form-check-input" type="radio" :name="questions[n].questionIndex" :value="index" @change="checkAnswer(questions[n].questionIndex, index)" :disabled="answeredQuestions[n]">
            <small class="form-check-label" for="">{{ index }}) {{ choice }}</small>
          </div>
        </div>
      </div>
      
    </div>
  </div>
  <div class="navbar bg-light fixed-bottom">
    <div class="container-fluid">
      <small :class="score">{{ currentScore }}</small>
    </div>
  </div>
export default {
  name: 'Quiz',
  data() {
    return {
      n: 0,
      answeredQuestions: [],
      currentScore: 0
    }
  },
  mounted() {
    front.on('questions', (data) => { 
      console.log(data) 
      this.$store.commit('quizQuestions', data);
      this.$store.commit('contentLoaded', true);
    });

    front.on('checkResponse', (response) => {
      console.log(response);
      if( response.answerCheck ){
        this.currentScore++; 
      }
      this.showNext(); 
    });
  },
  computed: {
    isLoaded() {
      return this.$store.getters.showLoader;
    },
    questions() {
      return this.$store.getters.quiz;
    },
    score() {
      return this.currentScore > 0 ? 'text-success' : 'text-muted';
    }
  },
  methods: {
    showPrevious() {
      if( this.n !== 0 ){
        this.n--
      }
    },
    showNext() {
      if( this.n < this.$store.getters.quiz.length ){
        this.n++
      }
    },
    checkAnswer(questionIndex, choice) {
      this.answeredQuestions.push(true);
      front.send('checkAnswer', {questionIndex: questionIndex, choice: choice});
    }
  }
}

I suspect that the issue lies with the name attribute of the radio inputs, however, I am uncertain. Does anyone have suggestions on how to address this matter?

Answer №1

Perhaps you could experiment with this approach: bind the answer for each question in your input value. When a new question is presented, if the answer has not been filled in previously, it will automatically default to null.

 <input class="form-check-input" type="radio" :name="questions[n].questionIndex" :value="questions[n].answer" @change="checkAnswer(questions[n].questionIndex, index)" :disabled="answeredQuestions[n]">

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

Retrieve the appended element's object

I am currently facing an issue with accessing elements that are automatically added by a library in my code. In my HTML, I have the following line: <div class="bonds" id="original" style="display:block;"></div> The library appends some elemen ...

Error: The expression `xmlDoc.load` returns a value of undefined, which is not an object

My current challenge involves loading an XML file using Javascript in IE, Firefox, and Safari. I have yet to find a function that works well across all three browsers. The load function I am currently using is similar to the one found in w3schools tutorial ...

JavaScript code to toggle the navigation bar on mobile devices

I am experiencing an issue with a script that is not performing the desired task. I am looking for a script that can add the Class "active" to a ul element with the id "btnMob0". Currently, my script looks like this: <script type="text/javascript"> ...

An Elegant Horizontal Navigation Bar with Smooth Scrolling and Div Anchor Tags

Looking to design a unique sticky horizontal scrolling navigation bar for displaying dates like 1800, 1801, 1802, etc. as part of a timeline project. The idea is to have the dates scroll horizontally within the navbar while I scroll down the page, alignin ...

Having an issue with Javascript onclick not updating div content upon first click

Having difficulty getting content from one div to another on the initial click. Some of my code: <a href="#" onClick="goPage1();">Feed</a> Function being called: function goPage1(){ $("#feed").html(""); get_jsonp_feed(); $("#con ...

AngularJS HTTP GET request failed to load the specified URL

I am working on a simple Angular code to read JSON data from a specific API URL. When I access the URL , it returns the following JSON data: Although the URL works fine when accessed through a browser, I'm facing issues while trying to read the same ...

Running Angular without dependencies causes it to malfunction

I recently ventured into the world of AngularJS and started by creating a module without any services or factories. Everything was running smoothly until I decided to introduce services and factories into my code. Suddenly, things stopped working. Here is ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

The table from datatables.net is failing to load with Ajax requests

Having trouble with v1.10 Datatables.net table not loading via ajax? The examples and documentation at datatables.net didn't provide a solution. Despite the table displaying, it shows "No data available in table". This issue is occurring in an older M ...

Is it possible to retry NTLM Authentication failure in Sails.JS?

Currently, my NodeJS application is built on Sails.JS and uses ntlm-express for NTLM authentication. Everything works smoothly when the authentication is successful. However, when it fails (such as when a Firefox user enters incorrect credentials), ntlm-ex ...

Pass the value of the search input to child components in Angular 2

Within my Angular 2 application, I am faced with the task of sending the value from an HTML search input to 3 child components only when the user pauses typing for 300ms and has entered a different value than what was previously in the input field. After r ...

What steps can I take to stop an AJAX request from causing the page to reload

I am facing an issue with my AJAX code where it reloads after a successful upload on the server side. Below is my HTML code that I have included. Any help or suggestions would be greatly appreciated. Thank you. function UploadVid(){ var file = $("#in ...

The background failed to display (potentially due to a hovering function)

I encountered an issue with a div that has a background image. Upon loading the page, the background image fails to display initially. However, when I hover over the div and then move my mouse elsewhere (due to a specific function described below), the bac ...

Update the table seamlessly to display fresh new data without the need to reload the entire page

I'm looking for a way to display recently added data on a listing page without having to reload the entire page. Currently, I have to refresh the page each time I add new data to my database in order to see the updates. Is there a way to view the new ...

Using Angular 2 to create an Observable type that mediates two separate http.get calls

In my ng2 service, I have a method that contains two http.get calls. Here is an example of the function: getInfo(userId: number): any { this.http .get(apiUrl, options) .map(response => response.json()) .subscribe(example => ...

Continuously encountering the modulerr error while working with AngularJS injections

In order to create an angular app with routes and controllers, I used the code below: (function() { angular.module('eCommerceApp', ['ngRoute']) .config('$routeProvider', function($routeProvider) { $rou ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

Creating a state in React and populating the rows of a Material-UI table with fixed data

I have implemented a table in the UI using the material-UI Table component. Initially, I added static data without using the state property of react. Now, I am looking for a way to assign static data to table rows by utilizing the state property. The code ...

Error: myFunction has not been declared

Can anyone figure out what's going on here? http://jsfiddle.net/sVT54/ <button onclick="myFunction()">Click me</button> <p id="demo"></p> function myFunction() { document.getElementById("demo").innerHTML="Hello World"; } ...

Place the child atop the stacked blocks

I need the .square div to always remain at the top, creating a visual effect where it appears as if the following section with its own .square is sliding up and the .square halts precisely at the position of the previous section's square. The code sn ...