When using VueJS checkboxes with object values bound to an array property, they do not get removed from the array when unchecked

Within my VueJS component, I am utilizing an array named selectedJobs to track checked checkboxes in an HTML table. The data displayed in the table is sourced from an array of objects called replenJobsList.

/* My Component */
    <template>
    ...
    <table>
    ...
    <tr v-for="replenJob in replenJobsList">
        <td>
            <input v-bind:id="'add-to-batch-' + replenJob.sku + replenJob.rplFrom + replenJob.replenTo"
                v-bind:value="{
                    id: 0,
                    manualMoveBatchId: 0,
                    modifyDate: new Date().getTime(),
                    moveFrom: replenJob.rplFrom,
                    moveTo: replenJob.replenTo,
                    sku: replenJob.sku,
                    skuDescription: replenJob.description,
                    status: 'active',
                    units: replenJob.unitsToReplenish
                }"
                v-model="selectedJobs"
                type="checkbox">
            <label v-bind:for="'add-to-batch-' + replenJob.sku + replenJob.rplFrom + replenJob.replenTo"></label>
        </td>
    </tr>
    ...
    </table>
    ...
    </template>
    ...
    data() {
        return {
            selectedJobs: [],
        }
    }
    

Upon evaluating

console.log(selectedJobs.length);
for all selected checkboxes, the correct length is displayed. However, upon unchecking a checkbox, the array length does not decrease by 1.

Moreover, upon rechecking the same checkbox, an additional object is added to the selectedJobs array instead of toggling its presence.

How can I ensure that checkboxes are accurately added to and removed from the selectedJobs array?

Answer №1

In order for correct tracking, it is recommended not to create the object in the markup. Instead, it should be done beforehand, possibly using a computed property.

new Vue({
  el: "#app",
  data: {
    replenJobsList: [
      { rplFrom: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a677e726f737a5f7a677e726f737a317c7072">[email protected]</a>', replenTo: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3c5ccce3c1c2d18dc0ccce">[email protected]</a>', sku: 1, description: '11111', unitsToReplenish: 33 },
      { rplFrom: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedbc6dfd3ced2dbfedbc6dfd3ced2db90ddd1d3">[email protected]</a>', replenTo: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="75131a1a351714075b161a18">[email protected]</a>', sku: 2, description: '22222', unitsToReplenish: 22 },
      { rplFrom: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8ddc0d9d5c8d4ddf8ddc0d9d5c8d4dd96dbd7d5">[email protected]</a>', replenTo: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d6b62624d6f6c7f236e6260">[email protected]</a>', sku: 3, description: '33333', unitsToReplenish: 11 },
    ],
    selectedJobs: [],
  },
  computed: {
    compJobsList() {
      return this.replenJobsList.map((job, index) => ({
          id: index,
          manualMoveBatchId: 0,
          modifyDate: new Date().getTime(),
          moveFrom: job.replFrom,
          moveTo: job.replenTo,
          sku: job.sku,
          skuDescription: job.description,
          status: 'active',
          units: job.unitsToReplenish,
        }));
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <thead>
      <tr><th>Jobs</th></tr>
    </thead>
    <tbody>
      <tr v-for="job in compJobsList" :key="job.id">
        <td>
          <input type="checkbox"
            :value="job" 
            v-model="selectedJobs">
            <label for="">{{ job.skuDescription }}</label>
        </td>
      </tr>
    </tbody>
  </table>
  <span>Checked jobs: {{ selectedJobs }}</span>
</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

Is it possible for JavaScript to be cached when it is located within the body tag of an HTML document?

Currently, I am exploring the topic of How to optimize HTML rendering speed, and came across the idea that scripts in the HEAD tag can be cached. I'm curious, is it possible to cache JavaScript in the BODY tag? If not, I wonder why YUI suggests placi ...

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

Contrasting an array of items with an array of Objects

I need to match the values in an array called ingredientName with a corresponding array of objects. Here is how they look: const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce']; let imageObjects = [ { ...

Using jQuery to create a checkbox that functions like a radio button

In my code, I have a bunch of checkbox elements placed in different containers as demonstrated below: $("input:checkbox").click(function() { var url = "http://example.com/results?&" var flag = false; var $box = $(this); var $facet = $box.val ...

Adjust the border color of Material UI's DatePicker

https://i.sstatic.net/ZvNOA.png Hello everyone, I am currently working with a DatePicker component from Material UI. My main goal is to change the border color of this component. I have attempted various methods such as modifying classes, adjusting the th ...

Express client with React and Webpack now supports Hot Reload feature

I currently have a setup using React, Webpack, and Express. Webpack bundles the React files and saves them in the /dist directory while running in watch mode during development. Any new changes are reflected in the dist directory. The Express server operat ...

Only capture website URLs in Google search results

Here is the code snippet I am working with: $urls = file_get_contents('https://www.google.com/#q=test'); preg_match_all('/\b(?:(?:https?|http):\/\/|www\.)[-a-z]*.com/i', $urls, $content); $i = 10; while ( $i < ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

Merge two arrays of objects containing Google Map coordinates

I am facing a challenge with merging two object arrays that have similar values. var Cars = [{ lat: 42, lng: -72 }, { lat: 40.7127837, lng: -74.0059413 }, { lat: 40.735657, lng: -74.1723667 }]; var Trucks = [{ lat: 43, lng ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Encountering an Enumeration Exception when trying to delete an element from a collection list using a foreach loop

I encountered an issue when attempting to remove an element from a list collection using foreach. I have searched online but have not found a clear explanation for the problem. If anyone has knowledge about this, please share the information. ...

Is getElementById in JavaScript reliable for multiple calls?

I am attempting to create a table cell that transforms into a textbox upon clicking, allowing for input to be entered and then displayed in the cell. Below is my JavaScript function: $(".cellConsigne").click(function () { var numId = this.id.substrin ...

The React/Redux application is experiencing difficulties with API calls, as they are returning empty responses and the actions are not being triggered

Hey there, I'm currently working on a React Native app and running into some issues with making API get requests. It seems like the response is throwing an error and the action isn't executing properly. I'll share my code below, so if anyone ...

Show a visual content in Grails Server Pages created through a specific class

In my class file, I have the image path displayed as shown below: String val; val+= "<img src=/"PATH_TO_FILE/" alt=/"sometext/">" Now, I am attempting to load the image in a gsp view within a div using jQuery from the val variable. The image is be ...

Stopping the Game Loop in Windows Phone 8.1 with WinJS

Despite everything working smoothly, I am facing an issue with stopping the game loop when the Start button is pressed and the app is moved to the background. The event handler for suspend, app.oncheckpoint = function(args) {}, does not seem to fire for t ...

Gatsby MDX fails to locate the desired page despite displaying the title and slug

Currently diving into the world of Gatsby and I've decided to implement MDX for my blog pages. Following a helpful tutorial here on programmatically creating pages. All seems well as I can view them in my GraphQL and displaying the list of articles i ...

How can we effectively create a table page object in Protractor that can handle various table selectors?

Recently, I have been delving into writing e2e tests in Protractor using page objects with JavaScript/Node.js. After reading numerous Stack Overflow posts and Julie's pages, as well as studying ProtractorPageObjects, I've come across an issue. A ...

Is it possible to update only the inner text of all elements throughout a webpage?

Scenario After coming across a thought-provoking XKCD comic, I decided to craft a script that would bring the comic's concept to life: javascript:var a=document.getElementsByTagName('body')[0].innerHTML;a=a.replace(/Program(\w\w+ ...

Is there a method to store only a portion of the string object in async-storage?

Is there a way to save only part of the string object into async-storage? For example, if the "result.userPrincipalName" contains "[email protected]", I want to save only the "bob23". What is the best method to achieve this? await AsyncStorage.setIt ...