Is Vue function only operating after editing and refreshing?

I'm facing an unusual issue in my Vue function where it only seems to work after causing an error intentionally and then refreshing the page. The code itself works fine, but there's a problem with the initialization process. Can someone provide some assistance?

Here's a brief overview:

When the user clicks on the button, a function named provjeriOdgovore is triggered. This function searches for all elements with the class name answer (the input fields), and then iterates through them to check if the input value is included in the variable odgovori. If the value matches, the program adds the class green-color to the element's classList; if not, it adds red-color instead.

The problematic code section:

HTML snippet:

<input class="answer" type="text">
<input class="answer" type="text">
<input class="answer" type="text">

<button :onclick="provjeriOdgovore()">Provjeri</button>

Javascript snippet:

const odgovori = [[long array of strings], [long array of strings], [long array of strings]]

export default {
  data() {
    return {
        provjeriOdgovore: () => {
          let questionDiv = document.getElementsByClassName("answer")
          for (let i = 0; i < questionDiv.length; i++) {
              let userInput = questionDiv[i].value.toLowerCase();
              questionDiv[i].classList.add("color-white")
              if (odgovori[i].includes(userInput)) {
                  console.log("tocno", questionDiv[i])
                  questionDiv[i].classList.add("green-color");
                  if (questionDiv[i].classList.length > 2) {
                      questionDiv[i].classList.remove("red-color");
                  }
              } else {
                  console.log("netocno" ,questionDiv[i])
                  questionDiv[i].classList.add("red-color");
                  if (questionDiv[i].classList.length > 2) {
                      questionDiv[i].classList.remove("green-color");
                  }
              } 
          }
      }
    }
  }
}

Answer №1

Make sure to include your function within the methods section:

methods: {
    checkAnswers() {
        let questionDiv = document.getElementsByClassName("answer");
        for (let i = 0; i < questionDiv.length; i++) {
            let userInput = questionDiv[i].value.toLowerCase();
            questionDiv[i].classList.add("color-white");
            if (answers[i].includes(userInput)) {
                console.log("correct", questionDiv[i]);
                questionDiv[i].classList.add("green-color");
                if (questionDiv[i].classList.length > 2) {
                    questionDiv[i].classList.remove("red-color");
                }
            } else {
                console.log("incorrect", questionDiv[i]);
                questionDiv[i].classList.add("red-color");
                if (questionDiv[i].classList.length > 2) {
                    questionDiv[i].classList.remove("green-color");
                }
            }
        }
    },
},

After defining the function, you can call it during the rendering process or in any lifecycle hook.

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

Internet Explorer's incompatibility with the window.location.href function

I'm having an issue with navigating to a new page using a callback from an AJAX post request specifically on Internet Explorer. Here is the code snippet causing the problem: $.ajax({ type: "POST", url: phpUrl, data: data, async: ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...

What is the best way to access and extract values from Material-UI TextFields within a Dialog component using React?

Here is the dialog that I am working with: <Dialog> <DialogContent sx={{ display: "flex", flexDirection: "column" }}> <TextField id="item-name" label="Item Name" /> <Tex ...

I can't seem to figure out why this isn't functioning properly

Upon examining the script, you'll notice the interval() function at the very bottom. The issue arises from bc-(AEfficiency*100)/5; monz+((AEfficiency*100)/5)((AFluencyAProduct)/100); For some reason, "bc" and "monz" remain unchanged. Why is that so? T ...

The issue of Select2 with AJAX getting hidden behind a modal is causing

I'm currently facing an issue with Select2 within a modal. The problem can be seen here: https://gyazo.com/a1f4eb91c7d6d8a3730bfb3ca610cde6 The search results are displaying behind the modal. How can I resolve this issue? I have gone through similar ...

Directive in AngularJS fails to trigger upon form reset

I encountered an issue with a directive used within a form, specifically when clicking on a button with the type reset. The problem can be replicated on this stackblitz link. The directive I'm using is quite simple - it sets the input in an error stat ...

continuously repeating css text animation

How do I create an animation loop that slides infinitely, repeating non-stop in full screen without breaking at 'hello5'? I want to display 3 rows of the same item from my items array. Not sure which CSS is causing the issue. The result I am loo ...

To set up MongoDB on your system, execute the following command: `npm install --

I've encountered a problem while attempting to install MongoDB on my personal computer for a Node project. I used the command line and ran npm install --save mongodb. Even though MongoDB appears in the dependencies section of my package.json file with ...

Attempting to display a singular form

Currently, I am working on a MERN app and encountering a small issue... I am developing an application where users can create rooms and within those rooms, they can plan their daily activities. It's similar to a TODO app but more intricate. I wanted ...

To achieve proper display of multiple boxes, it is essential for each box to be

My current approach involves adding boxes to the scene based on specific dimensions for height, width, and depth, and it works perfectly when the boxes are all square. https://i.sstatic.net/HdDSX.png However, the issue arises when I try to use a rectangu ...

Why isn't my prop available in the child component of Vue.js parent-child components yet?

Within the parent component Member.vue, I retrieve user and account data from the Vuex store using getters. <script> import { mapGetters } from 'vuex' import Profile from '@/components/Member/Profile.vue' export default { name: ...

What is the best method for serving cross-site content - JSONP, iframe, or a different approach?

In the process of developing an ad network, I am faced with the task of integrating third-party websites to include my JavaScript and replace specific divs with my content. Choosing which content to serve dynamically into these divs necessitates a cross-s ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

How to animate a left border shifting to the center using JavaScript

As I'm modifying my current div, I need to add a vertical line in the center of it. I've come across various solutions where a left border is added and then shifted using the left property by 50% (which effectively places it in the middle). Here ...

Ways to conceal the picture

Check out the JSfiddle link here for the full code. I'm having trouble with my slider as the last picture keeps collapsing underneath and is not hidden as it should be. I suspect this issue is causing the slider to malfunction. HTML <div class=" ...

Convert the numerical values from an array into an input field format

Currently, I have two inputs and an array with two number positions. The v-model in each input corresponds to a value in the array. Whenever a change is made in either input field, it reflects on the corresponding position in the array, which works perfect ...

The redirection link is created using techniques to point to either an href or a nuxt-link

Greetings! I am looking to present a webpage with a dynamically generated link. Below is my current code snippet. <template> <nuxt-link :to="seeProduct(item.sku.product.id).toString()"> <div> <span>Go to pr ...

Disabling an HTML attribute on a button prevents the ability to click on it

In my React application, I have a button component that looks like this: <button onClick={() =>alert('hi')} disabled={true}>test</button> When I removed the disabled attribute from the browser like so: <button disabled>test& ...

Using Double Quotes in v-b-tooltip in Vue Bootstrap

I recently implemented the vue bootstrap tooltip feature on my website. You can find more information about it here. Currently, I have a tooltip set up like this: <label>Encoding <feather-icon icon="AlertCircleIcon" class=" ...