The V-model fails to reflect changes when the checkbox list is updated

I am facing an issue with my checkboxes that are generated dynamically in a component using a v-for loop. Once a checkbox is checked, it is added to an array of selected checkboxes. The problem arises when a checked checkbox is removed - the v-model still includes the removed checkbox. How can I update the v-model to reflect changes in the array? I have already tried re-rendering the entire component, but that is not the ideal solution.

  <div v-for="player in players" :key="player.id">
  <input
    v-model="selectedPlayers"
    :value="player.id"
    type="checkbox"
    :id="player.id"
  />
  <label :for="player.id">
    {{ player.name }}
  </label>
</div>

Sandbox

Current Issue

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

Desired Solution

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

Answer №1

Make sure to manually remove data from the V-model when the component is no longer rendered.

To achieve this, filter the selectedPlayers from the @click handler to only include ids present in the new variable.

this.selectedPlayers = this.selectedPlayers.filter(
  id => players2.find(
    player => player.id === id
  )
)

Answer №2

Based on my understanding, you have an array called player2 that needs to be compared with the selectedPlayers array. The goal is to ensure that whatever is in the players2 array is also present in the selectedPlayers array. This can be achieved by using the map array function to iterate over the players2 array and extract only the ids of the players. These ids can then be stored in the selected players array, which is a reactive property that will automatically update the DOM. There is no need to re-render the component.

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  data() {
    return {
      selectedPlayers: [],
      players: [
        {name: "Arnold",id: "1"},
        {name: "Rambo",id: 2},
        {name: "Terminator",id: 3},
        {name: "Titan",id: 4},
        {name: "Odin",id: 5},
      ],
      players2: [
        {name: "Titan",id: 4},
        {name: "Odin",id: 5},
      ],
    };
  },
  methods: {
    clicked() {
      this.players = this.players2;
      this.selectedPlayers = this.players2.map(p => p.id);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  If you check all checkboxes and press the button, the array still contains all elements
  <div v-for="player in players" :key="player.id">
    <input v-model="selectedPlayers" :key="players.length" :value="player.id" type="checkbox" :id="player.id" />
    <label :for="player.id">
        {{ player.name }}
      </label>
  </div>
  {{ selectedPlayers }}
  <button @click="clicked">Press me</button>
</div>

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

Sending router data as a prop

When passing data for the route, I am doing it like this: /route { path: '/name/:nameSlug', name: 'NameItem', props: true, components: { home: Name } }, To link to the component in the router: <router-link :to=" ...

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

Using conditional rendering to set an icon in a ChipField component in React Admin

One feature in my React Admin App is a Datagrid with a ChipField displaying a text property. I want to enhance this by adding an icon to the ChipField using the icon prop, which should change based on the text value. This is my current approach: expor ...

Tips on updating the default checkbox dynamically based on the current checkbox using JavaScript

Seeking to enhance the design of a Perl-generated form with custom CSS effects, rather than relying on the default Perl form. Despite successful functionality, encountering an issue where radio button focus reverts to default selection (Date) after submitt ...

Is it possible for an ajax request to complete even if a page redirection occurs?

In my current project, I am attempting to generate a temporary URL for a local image and submit it to Google for an Image Search. I need this URL to be transient and automatically deleted after the search is complete. Here's the code snippet that I ha ...

How can you access the query in Next.js API when req.query is initially set to undefined?

Is there a way to compare the value of req.query with the cookies on the site, even when req.query is undefined upon initial load? How can this be addressed? export default async function handler(req, res) { const { method } = req; const userId = req ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

When updating a form, it is essential to display select box data from the database effortlessly. It is also important to ensure that the select box data's id is

In my current project, a quasar (vuejs) app, I am faced with an issue related to an update form functionality. The challenge I am encountering is that when I submit the form without making any changes to the select box, it submits the label as a string ins ...

How can Vue i18n be utilized as a JavaScript object instead of within the template?

Can vue and vue-i18n be utilized solely with JavaScript (as an object) instead of in the template? Is it feasible to implement it in a scenario similar to window.confirm? Appreciate your assistance. ...

The process of updating JSON data based on changes triggered by DOM events such as drag and drop

One challenge I am facing involves a Vue component used to render child components based on JSON data. The goal is to allow users to move and add components by dragging and dropping DOM elements on the page, using tools like jQuery draggable, droppable, an ...

I have successfully implemented an onChange function with its corresponding set of parameters. However, I now desire to extend its functionality by incorporating

I have an onchange function that triggers when the "pending" option is selected in a select dropdown menu. This function adds a predefined value to an input field. However, I also want this functionality to apply when the page loads. Currently, the "pendin ...

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...

Methods for displaying data on the client side using express, MongoDB, and jade

I'm currently working on displaying data retrieved from my database using node.js, Express, and MongoDB. I successfully see the data in the console, but now I need to output it on the front-end using Jade. Here is the data I have retrieved: { date: ...

Creating responsive arrow heads using D3: A step-by-step guide

Currently, I am working on creating a thermometer-style bar chart using D3.js version 3. While I have successfully created a basic responsive rectangle with two filled colors, I am facing difficulties in figuring out how to add arrow heads to the design. B ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

Is there a method to achieve greater accuracy when dividing a large number?

My requirement involves operating on Big Numbers, and I need the results to maintain precision, as demonstrated below: const BN = require('bn.js'); var a = 11060622312717714974 var b = 1570481433500000000000; console.log(a/b); //0.00704282271460 ...

Is there a way to utilize a single function on two separate div elements?

Looking for a way to optimize my code that contains the addRow() and deleteRow() functions. Currently, I have duplicated these functions for both radio buttons and checkboxes. Is there a more efficient way to achieve this? function addRow(tableID) { ...

How to dynamically load a file based on the chosen option value in React

Two select textboxes on my page are named Choose City and Choose District. I also have some files related to cities and districts: // cities.js const cities = { "01": { "name": "City 1", "code": "01" }, ...

Regarding passing input into a JavaScript class method that is exported through the exports keyword

The inquiry at hand relates to ExtendScript code, however, I believe it should be independent of any specific javascript implementation. If we have the following in a JS library file (base64.js) exports.encode64 = encoder('+/'); //... function ...

Clear the Material-UI textfield upon form submission

After submitting the form, how can I clear the value from the TextField? All of the components in my code are functional components, not class ones. The example below shows one of the TextFields, with others similar to it. Currently, setting type='sea ...