How can I prevent v-model from filling multiple fields?

Having just started with Vue.js, I've managed to solve most of the issues I've encountered so far, but there's one that's stumping me.

I'm working on displaying a list of posts fetched from an API and I want to include a comments box for each post. Posting comments to the API is functioning correctly and adds them without any issues. However, I'm facing a problem where any text entered in one input field is being duplicated in all the other input fields due to the v-model binding.

                    <div class="row" v-if="">
                        <div class="col-md-11">
                            <input type="text"  class="form-control" value="" title=""
                                   placeholder="Add comments here.." v-model="note.note">
                        </div>
                        <div class="col-md-1">
                                <button type="button" class="btn btn-default" style="margin-left: -1.5rem" v-on:click="addNote(task.id)">Add Comment</button>
                        </div>
                    </div>

JS:

  addNote: function (id) {
        if (this.note.note) {
            Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');

            this.$http.post('api/note/create/' + id, this.note).then(function (response) {
                this.fetchTaskList();
            });

        } 
    }

Screenshot:

https://i.sstatic.net/ispmR.png

Is there a different directive that would be more appropriate for this situation? Or is there another workaround?

Answer №1

To accomplish this task, utilize the index in the v-for loop to bind each box to the notes' comment property. Here's how you can do it:

<!-- Use the index to keep track of the loop position -->
<div v-for="(note, index) in notes">
  {{ note.note }}
   <!-- Bind the input to the comment based on the index -->
  <input v-model="notes[index].comment" />
</div>

Next, ensure to set up the necessary data in the component:

data: {
  notes: [
    {note: 'note 1', comment: ''},
    {note: 'note 2', comment: ''},
    {note: 'note 3', comment: ''}
  ]
}

For a live example, check out the JSFiddle link provided: https://jsfiddle.net/efxzmq9s/

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

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

Discovering the final insert ids in Laravel 4: A step-by-step guide

Currently working with Laravel 4 and utilizing a table named 'documents'. The data insertion process into the Document table is done using the Document::insert() function as illustrated in my code snippet below: $statuses = array(); foreach($con ...

Testing units with Jest using ES6 import syntax instead of module.exports

There's a script I created that contains all the logic in a single const variable, similar to Moment.js. I'd like to test the functions from this script using Jest. Unfortunately, using module.exports won't work when I publish the script. ...

Nodejs functions properly on a local machine, however, it encounters issues when deployed on a VPS

My nodejs/javascript code seems to be running fine on my local pc, but when I try to run it on my vps, it's not working properly. Even though I have the same node_modules installed and the code is identical. Here's a snippet of my code for refere ...

Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below: $scope.myRecs = [{country: 'Ireland', city: 'Dublin&apos ...

Is there a way to modify the URL of a page in Nuxt SSR mode without having to reload the entire page?

Creating a Master Detail View where the list and detail are displayed side by side on desktop, but on separate pages on mobile. See image for reference. The list may contain anywhere from 500 to 10,000 items I tested both scenarios with 10,000 items, but y ...

How can you display varying information based on a dropdown selection using Material-UI's Select component?

By default, the Select component is populated with the correct data. However, I am facing an issue where selecting the "InReview" option should display the options inside the statusArr and remove the previous ones. Thank you in advance for your help. Her ...

Transition one background image into another using background positioning

Snippet of code: https://jsfiddle.net/foy4m43j/ HTML: <div id="background"></div> CSS: #background { background-image: url("http://i.imgur.com/hH9IWA0.png"); background-position: 0 0; background-repeat: repea ...

Is it possible to delete an element from a JSON file by solely utilizing the element's ID?

I'm fairly new to JavaScript and I've tried various online solutions without success. Currently, I'm working on creating a backend for a todo list application where I aim to implement the feature to delete items from the list. Below is the ...

What is the method for adding an event listener in AngularJS within an ng-repeat iteration?

I'm completely new to AngularJS and currently working on building a photo gallery. The basic idea is to have an initial page displaying thumbnail photos from Twitter and Instagram using an AngularJS ng-repeat loop. When a user hovers over an image, I ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

What could be the reason for my post jQuery Ajax request sending JSON data?

After downloading some code, I came across the following fragment: function FetchCommentsBySessionIDWCF_JSON() { varType = "POST"; varUrl = "service/CommentSessionIDWCFService.svc/FetchCommentsByPost"; varData = ' ...

"Troubleshooting why React fails to update an array state

When I click the update name button, the state is not changing properly using setState. I want to update the persons variable and have it reflect in the DOM as well. Any ideas on how to achieve this? App.js import React, { Component } from "react"; impo ...

Can the site be shown in the background?

I have a unique idea for a games website that I want to share. It's a bit difficult to explain, so please bear with me as I try to convey my vision! The inspiration for this project comes from a website called . Have you seen it before? The concept i ...

Unable to properly structure data in JSON request

Trying to fill JSON request with data from phpsearch.php file (displayed below) <?php include "base.php"; $name = $_GET["name"]; $query = "SELECT lat, lng FROM markers WHERE name = '".$name."'"; $result = mysql_query($query); $json = array(); ...

JavaScript and Angular are used to activate form validation

Update: If I want to fill out the AngularJS Forms using the following code snippet: document.getElementById("username").value = "ZSAdmin" document.getElementById("password").value = "SuperSecure101" How can I trigger the AngularJS Form validation befo ...

The passing of query string parameters from JavaScript to a PHP processing script is ineffective

I am looking to dynamically populate a jQWidgets listbox control on my webpage with data retrieved from a MySQL database table once the page has finished loading and rendering. PARTIAL SOLUTION: You can find a solution here. NEW PROBLEM: I have created a ...

Focusing on maximizing the potential of individual elements within an array

I have an array of values and I am looking to create a new array where specific values are assigned based on the values in the original array. For instance: My initial array: var values = [1, 2, 3, 4] The new array I want: [red, green, blue, black] I ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result. Here is my current code: axios .post("/post ...