Creating a form in Vue that dynamically generates checkbox options

In my Vue application, I have a dynamically generated form with v-models within a loop. Everything is working correctly except for checkboxes. The issue I am facing is that the v-model is affecting all the loops instead of just one, unlike with the input type text. Can anyone help me find a solution to this problem? Below is the Vue code:

<fieldset>
  <div class="form-row mb-2" v-for="input, index in journal" :key="index">
    <div class="col-auto">
      <label for="date">Data</label>
      <Datepicker v-model="input.date" input-class="form-control" :input-attr="{id: 'date', name: 'date'}" style="width: 100%;" />
    </div>
    <div class="col-md-2">
      <label for="timeStart">Od</label>
      <Datepicker type="time" v-model="input.timeStart" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeStart', name: 'timeStart'}" style="width: 100%;" />
    </div>
    <div class="col-md-2">
      <label for="timeEnd">Do</label>
      <Datepicker type="time" v-model="input.timeEnd" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeEnd', name: 'timeEnd'}" style="width: 100%;" />
    </div>
    <div class="col-md-2">
      <label for="players">Lista obecności</label>
      <div class="form-check" v-for="item in input.players">
        <input v-model="item.checked" type="checkbox" class="form-check-input" :id="'id-'+item.id+'set'+index">
        <label class="form-check-label" :for="'id-'+item.id+'set'+index">{{ item.fullName }}</label>
      </div>
    </div>
    <div class="col-auto">
      <label for="description">Opis</label>
      <textarea v-model="input.description" class="form-control" rows="7" id="description" placeholder="Opis"></textarea>
    </div>
    <div class="col-auto" @click="addInput" v-show="index == journal.length-1 && journal.length < 16">
      <ButtonVue style="margin-top: 30px;" title="Dodaj" type="button" cancelWidth="true" color="btn-success"><i class="fas fa-plus"></i></ButtonVue>
    </div>
    <div class="col-auto align-self-start" @click="removeInput(index)" v-show="index || ( !index && journal.length > 1)">
      <ButtonVue style="margin-top: 30px;" title="Usuń" type="button" cancelWidth="true" color="btn-danger"><i class="fas fa-minus"></i></ButtonVue>
    </div>
  </div>
</fieldset>
 
data() {
  return {
    contact: [],
    journal: [{
      date: "",
      timeStart: "",
      timeEnd: "",
      players: "",
      description: ""
    }],
    contacts: [],
  }
},

Methods:

Method for creating dynamic form

addInput() {
  this.journal.push({
    date: "",
    timeStart: "",
    timeEnd: "",
    players: this.contact,
     description: ""
  });
},

And here is the method which gets players from contacts

getContacts() {
  this.pageLoader = true;
  this.$http.get('/pkpar/get-contacts')
    .then(({
      data
     }) => {
     this.contacts = data.contacts;
     for(let i=0; i<this.contacts.length; i++)
     {   
     this.contact.push({'id': this.contacts[i]['id'], 'fullName' : 
     this.contacts[i]['fullName'], 'checked': true});
     }    
     this.journal[0].players = this.contact;
     this.pageLoader = false;
    })
    .catch(error => {
        console.log(error);
    });
}, 

Answer №1

When using your addInput method, keep in mind that it creates and adds a new object to the journal array. However, each object created in this way includes a players property that actually references the same array (this.contact).

To better understand this concept, check out The Difference Between Values and References in JavaScript

If you want to address this issue, the simplest approach (though not the most efficient) is to make copies of the array and objects inside for each new journal:

addInput() {
  this.journal.push({
    date: "",
    timeStart: "",
    timeEnd: "",
    players: this.contact.map((player) => ({ ...player })),
    description: ""
  });
},

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

Assessing efficiency through the lens of SeleniumWebDriver versus native JavaScript

Imagine a scenario where an action is triggered by clicking a button on a webpage. Let's say this action takes X seconds to complete, and during this time a div appears in the center of the page. Once the action is done, the div disappears, and focus ...

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

What are some strategies for preventing a child component from triggering a re-render of its parent component in React Native?

My child component is causing the parent component to re-render when it's clicked, which is not the desired behavior. I initially thought that removing all the setState() functions in the child component would prevent this, but then I realized that As ...

Error: The function clickHandler has been referenced before it was declared or it has already been declared

Since I started using JSLint, I have encountered the common issues of "used before defined" and "is already defined." While I found solutions for some problems, I am currently stuck. Here is a snippet of my code: var foo; foo = addEventListener("click" ...

Execute a VueJS API call every 20 minutes

I am retrieving data from an API endpoint to display information about coin names. I would like this information to update every 20 minutes, but for testing purposes, I have set it to refresh every 500 milliseconds. However, my current approach of fetching ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...

Creating a plane in Three.js using points along different axes

My goal is to construct a plane that intersects the points (2, 3, 12) on the x, y, and z axes respectively (equivalently, the equation of the plane is 6x + 4y + z = 12). So far, I have attempted to generate a flat plane and rotate it around the three axes ...

Creating seamless transitions between pages using hyperlinks

On the homepage, there are cards that list various policies with a "details" button above them. Clicking on this button should take me to the specific details page for that policy. However, each product can only have one type assigned to it. For instance: ...

Encountering a Microsoft error while trying to install jsdom with node.js

I'm currently in the process of setting up jsdom on my system. I found a helpful guide at but encountered the following issue: C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.InvalidPlatform .Targets(23,7): e ...

Using Node.JS, Sequelize, and Moment.JS to format dates

Seeking help on formatting a date loaded from Sequelize in my database. I'm working on a blog and need to display the creation date of an article. Here's my route: app.get("/", (req,res) =>{ Article.findAll({ order:[ [ ...

The information retrieved from an API fails to populate the table on the NextJS platform

I am facing an issue while trying to populate a table using an API call in NextJS. I have used the getStaticProps function to retrieve the data and pass it to the component. However, when I attempted to use the map() function to iterate over the data objec ...

Differences between angular.isDefined() and obj.hasOwnProperty()

When working with angular.js, how should I handle objects that may or may not have a status? What are the pros and cons of using angular.isDefined() versus item.hasOwnProperty() in this scenario? var checkStatus = function(item){ if(angular.isDefine ...

Exploring the intricacies of React Router parameters

I have been facing some issues with my routing setup. Specifically, I have a static route called list and a dynamic route called user/:id. The problem arises when navigating between these two pages. (1) Whenever I navigate to the list route from the user/: ...

How to properly configure links within a row of an Element UI table (Is it as simple as it seems?)

I am facing a challenge with displaying the user's projects in Element UI using a table. Since Element UI doesn't support <tr></tr>, I am unsure of how to proceed. The goal is to showcase the user's projects and allow basic CRUD ...

Scraping the Web with Python: Harnessing the Power of Selenium and

Seeking assistance with a problem I've encountered. I'm attempting to extract numbers from a specific website (link provided in the code below). Since the website utilizes JavaScript, my approach involves using selenium to load the page first and ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

When the "next" button is clicked on Datatables, the next set of 10 items

I am currently working on creating a table with pagination using datatables. The data is being fetched via ajax, which returns 10 data entries at a time. However, I am facing an issue where the first call only fetches the initial 10 data from the ajax call ...