The button on my VUE 3 quiz app is not changing to 'Finish' when I reach the final question

Struggling with my Vue 3 quiz app - everything works perfectly until I reach the last question. The button text should change to 'Finish' once the final question is loaded. Despite hours of searching and even using copilot, I still can't find the error. How can I update the button text after reaching the last question in Vue?

<script setup>
import { ref, computed } from 'vue'

const questions = ref([
  {
    question: 'How many books are in the kjva bible?',
    answer: 0,
    options: [
      '80',
      '32',
      '60',
    ],
    selected: null
  },
  {
    question: "What is the name of Israel's first king?",
    answer: 2,
    options: [
      'David',
      'Asa',
      'Saul',
    ],
    selected: null
  },
  {
    question: 'Salvation is of the...?',
    answer: 1,
    options: [
      'Egyptians',
      'Jews',
      'Edomites',
    ],
    selected: null
  }
])

const quizCompleted = ref(false)
const currentQuestion = ref(0)
const score = computed(() => {
  let value = 0
  questions.value.map(q => {
    if(q.selected == q.answer) {
      value++
    }
  })
  return value
})

const getCurrentQuestion = computed(() => {
  let question = questions.value[currentQuestion.value]
  questions.index = question.value
  return question 
})

const setAnswer = evt => {
  questions.value[currentQuestion.value].selected = evt.target.value
  evt.target.value = null
}

const nextQuestion = () => {
  if(currentQuestion.value < questions.value.length -1) {
    currentQuestion.value++
    console.log('currentQuestion.value type:', typeof currentQuestion.va...
    
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Montserrat', sans-serif;
}

body {
  background-color: #271C36;
  color: #fff;
}
</style>


I've attempted to debug by console logging the nextQuestion function without success. I suspect that the issue lies in the button logic but I'm unsure.

Answer №1

getCurrentQuestion retrieves a question without an index property. This means that getCurrentQuestion.index (undefined) will never be equal to questions.length - 1 (2).

The correct comparison should be:

currentQuestion === questions.length - 1
.


A few additional points to consider:

  • I suggest renaming currentQuestion to either currentIndex or currentQuestionIndex
  • Avoid using loose comparison operators like (== and !=)
  • You can skip using setAnswer by utilizing v-model.number
  • You can omit the use of getCurrentQuestion. Instead, you could implement:
<section
    class="quiz"
    v-for="current in [questions[currentQuestion]]"
    :key="current.question"
>
    <!-- utilize `current` -->
</section>

View it in action here

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

Sorting a list with anchor tags alphabetically using Javascript/JQuery

Here is a list of services: <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Copy service for files from folder 12</a></li> <li><a href='http://site/Service.aspx? ...

Is there a way for me to immediately send data after receiving it?

When I try to perform onPress={() => kakaoLosing() I am attempting to retrieve data (profile) from getProfile using async await and immediately dispatch that data to KAKAOLOG_IN_REQUEST, This is my current code snippet: import { ...

What is the best way to showcase information within a node framework?

I am looking to create a family tree using the MVC framework. Furthermore, I need to be able to insert data with relationships. I have object data that I would like to display along with its entities in a node structure. Any assistance on this matter wou ...

What is the best way to choose the initial p tag from an HTML document encoded as a string?

When retrieving data from a headless CMS, the content is often returned as a string format like this: <div> <p>1st p tag</p> <p>2nd p tag</p> </div> To target and select the first paragraph tag (p), you can extract ...

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

Unable to change the visibility of blockquotes using jquery

Currently, I am delving into the world of basic JQuery functions. My main focus right now is figuring out how to display the active blockquote while keeping the others closed or closing them. Essentially, creating a toggle effect where only one blockquote ...

The HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

Conceal when dates align

In my events list, I have dates displayed and would like to hide any end dates that are the same as the start dates. For instance; <span class="start_date">Wed 23rd January</span> <span class="end_date">Wed 23rd January</span> I ...

Send information using AJAX within a .NET integrated browser

In our current setup, we utilize a .NET embedded browser to showcase an HTML page that is generated by applying an XSLT file to an XML file using .NET. This process results in HTML content displayed within the embedded browser through the DocumentText prop ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

Activate when every single pixel within an element is see-through

I've designed a web page that includes two canvas elements stacked on top of each other. The purpose of this setup is to allow me to "erase" the top canvas and reveal an image loaded into the bottom canvas. So far, this functionality has been working ...

Having trouble with the Tap to copy discount code function not working in the Shopify cart drawer?

Our goal is to implement tap to copy functionality for code snippets on our Shopify website. It works seamlessly on the product detail page, but in the cart drawer, it only functions properly after the second page load. {% if cart.total_price > 0 % ...

Ways to eliminate bottom margin of text area in vuetify

Greetings, I am facing an issue with the following code snippet: <v-text-field :rules="rules" v-model="exam.title" class="exam-title ma-0 pa-0" ></v-text-field> <v-text-field class="exam-title ma-0 pa-0"></v-text-field& ...

"Having trouble implementing sorting functionality on a click event in a React application with Material-UI table

Default behavior displays data in ascending order. Clicking on the table header should toggle between descending and ascending orders. Load Data in ascending order -> On click, change to descending order -> Again on click, change to ascending -> ...

Combining strings and variables in Vue.js with the use of bootstrap-vue syntax

Hey, I'm facing a little syntax hiccup with '="collapse-{{ product.id }}"' in both the b-button and b-collapse. Any ideas on how to properly structure this? Just looking to set up a unique ID that connects the button to the collaps ...

Exploring the process of passing parameters in Material-UI React styled components

Recently, I developed a new component const CategoryDialog = (props) => { const classes = useStyles(); console.log(props); return ( <div> <Dialog fullScreen open={props.dilaogOpenProp} TransitionCompone ...

The results of running 'npm run dev' and 'npm run build prod' are different from each other

Currently, I am in the process of developing a progressive web app using Vue.js. During development, I utilize the command npm run dev to initiate the local server that serves the files over at http://localhost:8080/. When it comes time to build for produ ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...