Utilizing v-model dynamically to showcase the outcomes of a specific property within a v-for iteration

As I iterate over an array using v-for, the number of items in this array varies each time. Currently, I am able to input values into the fields and have them correctly update the data property associated with them.

However, there are two issues that need resolution:

-Firstly, when I click on edit as shown in the code, the current value of the property does not appear in the input field bound by v-model (resulting in an empty input box). It seems to work only one way. (I can input new data which gets reflected in the data property as mentioned earlier)

-Secondly, I want to submit the updated data to the server using something like axios. The challenge here is how to assign these new values to variables for submission since the number of values may vary each time.

Below is the component code snippet:

<template>
    <div class="container">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Options</th>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Student Id</th>
                    <th v-for="quiz in quizzes">
                        {{ quiz.quiz_name }}
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(student, index) in students">
                    <td v-if="!editing_user || !currentStudent(student)">
                        <button class="btn btn-primary" @click="edit(student, index)" :disabled="editing_user == true">
                            Edit
                        </button>
                    </td>
                    <td v-if="editing_user && currentStudent(student)">
                        <button class="btn btn-primary btn-xs">Update</button>
                        <a @click="cancelEdit">
                            Cancel
                        </a>
                    </td>
                    <td>
                        {{ index }}
                    </td>
                    <td>
                        {{ student.full_name }}
                    </td>
                    <td>
                        {{ student.email }}
                    </td>
                    <td>
                        {{ student.secret_id.secret_id }}
                    </td>
                    <td v-for="quiz in student.quizzes" v-if="!editing_user || !currentStudent(student)">
                        {{ quiz.pivot.score }}
                    </td>
                    <td v-for="(quiz, index) in student.quizzes" v-if="editing_user && currentStudent(student)">
                        <input v-model="quiz_scores[index]">
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
        props: ['students', 'quizzes'],
        data: function () {
            return {
                editing_user: '',
                index: '',
                quiz_scores: []
            };
        },
        mounted() {
            //
        },
        methods: {
            edit(student, index) {
                this.editing_user = student,
                this.index = index,
            },
            cancelEdit() {
                this.editing_user = '',
                this.index = '',
                this.quiz_scores = [],
            },
            currentStudent(student) {
                return this.editing_user == student
            }
        },
    }
</script>

This code excerpt is a work in progress. Any suggestions or advice on what steps to take next would be greatly appreciated.

Answer №1

When you perform the edit action, your inputs may be empty because the v-model quiz_scores[index] is always empty. To populate it on "Edit" click, you can do the following:

edit(student, index) {
  this.editing_user = student
  this.index = index
  this.editing = true
  student.quizzes.forEach( q => {
    this.quiz_scores.push(q.pivot.score)
  })
}

Similarly, for updating, you can create a variable new_scores: {} as an empty data structure and fill it when clicking "Update" with the necessary information (such as current student object or array of scores). Then utilize new_scores to send a request to post the data to your server.

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

Unable to reset the input value to an empty string

I have created a table with a search bar feature that filters the data when the search button is clicked and resets the filter to show unfiltered data when the clear button is clicked. However, the current input value is not clearing from the display even ...

Dynamic field refreshed on server side upon second button press

I'm encountering an issue where a hidden field that I update via Javascript only reflects the new value after clicking a button twice. Surprisingly, I can view the updated hidden field value when inspecting it through the browser. Default.aspx <s ...

The CSS files undergo modifications when executing the command "npm run dev"

I've been working on an open-source project where I encountered a bug. Even when there are no images to display, the "Load More" button in the web browser extension still appears. To fix this, I decided to add the class `removeButton` to the button an ...

Facing issue with "npm run build" command while building on VSTS/Azure DevOps

I encountered a strange issue with my Vue project during deployment on the Azure DevOps platform. Everything worked fine on my local machine, but when I tried to run "npm run build" on Azure DevOps, I started getting multiple "ELIFECYCLE" errors that left ...

Do two Express JS applications run on separate threads?

Running two express apps on different ports raises the question of whether they assign themselves to different cores, knowing that express typically runs on a single thread. The cluster module, however, replicates the express app and allows them to utiliz ...

Is there a way to retrieve and utilize this JSON data within Vue.js?

Here is the JSON output: { "Response": { "Error": { "ErrorCode": 0, "ErrorMessage": "" }, "Results": { "FareBreakdown": [{ ...

Trigger jQuery Waypoints Only Once

Utilizing , I am seeking to trigger a specific action when the user scrolls down to the section marked with the class div1. However, the action should only occur once and not repeatedly each time the user reaches that point. — just once $('.div1&ap ...

Send the user back to the previous page once authentication is complete

I am integrating Google authentication through Passport in my web application and I am facing an issue with redirecting the user back to the original page they requested after a successful sign-in. It seems like the use of location.reload() might be causin ...

Leveraging React Hooks for managing the Data Provider and Data Context functionality

Currently, I am revamping my DataProvider by upgrading it from a class component to a functional component utilizing React Hooks. I suspect that the issue lies in how I am setting up my context consumer, but I am struggling to find an effective way to tes ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Trouble with Adding and Showing Arrays

function resetValues() { var p = parseFloat($("#IA").val()); var q = parseFloat($("#IB").val()); var m = parseFloat($("#CGCD").val()); var aR = []; aR.push("GCD(" + p + "," + q + ")=" + m); document.getElementById("PGCD").innerHTM ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

Tips for creating an infinite repeating loop in jQuery

I'm attempting to create a jQuery infinite loop featuring images within a div. I've experimented with using the setInterval function, but encountered an issue where the animation starts after a 3-second delay and does not seamlessly repeat itself ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Contrast between employing element selector for concealment and activation tasks

I can't figure out why $('#mdiv input')[1].hide(); isn't working while $('#mdiv input')[1].click(); works perfectly fine. Firstly, I'm curious to understand why. Secondly, how can I get it to work without knowing the id ...

Include a Vue component within another Vue component in a Laravel application using VueJs

I've recently integrated Vue.js into my Laravel project and encountered an issue when trying to call a component within another component. After running the command npm run dev, I received a webpack error. Here is the code snippet from my parent comp ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

What is the best way to troubleshoot a quasar typescript file type error?

Currently, I am delving into Quasar using TypeScript and encountering a type error while working on file uploads. Here is the snippet of my code where the type error arises specifically in the parameter of the form.append() method. The error message read ...

combine a pair of elements simultaneously

I recently developed a nested directive for a multitabbed form, and here is a simplified version: <outer> <inner heading="a" src="'a.html'" active="true"></inner> <inner heading="b" src="'b.html'"></inner ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...