Is the Vue "Unchecking" feature not properly deleting data from the array?

I need to update my function to handle the removal of a networkAudience when its corresponding checkbox is unchecked. Currently, the networkAudience is being added to the array when checked, but not removed when unchecked.

What changes should I make to ensure that a networkAudience is removed if its checkbox is unchecked?

new Vue({
  el: '#app',
  data: {
    networkAudience: {}
    selected:[]
  },
  methods: {
    netToggle(networkAudience)
        {     
            if(!this.selected.includes(networkAudience)) 
                this.selected.push(networkAudience);
            else 
                this.selected.splice(this.selected.indexOf(networkAudience), 1);
  
        }

  }
});
<div v-for="(networkAudience, index) in networkAudiences" : key="index">
  <tr>
    <input
      class="form-check-input"
      type="checkbox"
      :checked="selected.includes(networkAudience)"
      @click="netToggle(networkAudience)"
    >
  </tr>
</div>

After unchecking a box, the output should only show one object, but currently, the unchecked box duplicates the object.

https://i.sstatic.net/2Tp1l.png

Answer №1

Based on my understanding of your explanation, you can implement the solution provided below:

new Vue({
  el: '#app',
  data() {
    return {
      networkAudiences: [{id:1, name:'aaa'}, {id:2, name: 'bbb'}, {id:3, name: 'ccc'}],
      networkAudience: {},
      selected: []
    }
  },
  methods: {
    netToggle(networkAudience) {     
      if(!this.selected.includes(networkAudience)) {
        this.selected.push(networkAudience);
      } else {
        this.selected.splice(this.selected.indexOf(networkAudience), 1);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(networkAudience, index) in networkAudiences" :key="index">
    <div>
      <label :for="networkAudience.id">{{ networkAudience.name }}</label>
      <input
        class="form-check-input"
        type="checkbox"
        :id="networkAudience.id"
        :value="networkAudiences[index]"
        @input="netToggle(networkAudience)"
      />
    </div>
  </div>
  {{selected}}
</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

No matter the way I input the URL in the AJAX call, the response always comes back as successful

I ran into an issue with my ajax request. It was supposed to be a GET request that returned some data, but no matter how I configured the URL, it always gave a success response even when it didn't actually succeed. var id = 5; $.ajax({ type: ...

Enhance Select Dropdown in AngularJS with Grouping and Default Selection

I am facing an issue with a form that includes a SELECT element. I have successfully loaded the possible values in my controller from a function that retrieves data from a database and groups the options by a group name. Although the list of options is lo ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

Update a JQuery function for an input field following an innerHTML command

Using JQuery to check the file size and name from an html file input field can be a useful tool. The input field in question looks like this: <div id="uploadFile_div"> <input name="source" id="imageFile" type="file" style ="border: 1px solid ...

Having a Jquery resizing problem? No worries! When the width is less than 768, simply enable the click option. And when the width is

HTML <div class="profile"> <a href="#" class="hoverdropdown" onclick="return false;">Profile</a> <ul class="dropdown" style="display: none;"> <li><a href="#">Dashboard&l ...

Creating a new object in an empty array within my profile model (mongodb/mongoose) is simple. Just follow these steps to successfully add a

Presenting my Profile model: const ProfileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User", }, company: String, website: String, location: String, status: { type: String, require ...

Activate the HTML drop-down option upon selecting the radio button, or the other way around

I'm attempting to accomplish a task. Below is the code snippet I am working with: <form> <input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type=&apo ...

Adjust the color of the Icon within the tab in Material-UI

I'm attempting to change the color of the tab icon that is highlighted while keeping the others unchanged, but I am struggling to find a solution. I am using a MUI component inside the icon button. <Tab icon={ ...

When using Jquery, hovering over an element will cause the full title to be

I have created a toggle div that displays an ellipsis (...) when the long title is longer than 30 characters. Now, I want the full text of the long title to appear when hovering over the div. Check out this JS Fiddle for reference. JS $('#popu ...

Position a div element after another using the :after pseudo-element

My goal is simple to explain, but I have exhausted all my efforts trying to achieve it. I am hoping for the ★ symbol to appear immediately after the number 06 using jQuery. Any assistance would be greatly appreciated. The numbers are generated by a s ...

Converting JQuery Object (Ajax-response) to an Array Containing Keys and Values

When I make an $.ajax request, the response I receive looks like this: https://i.sstatic.net/UfnfQ.jpg (please don't worry about the Russian symbols, they are just strings of text:)) I am aware that when PHP sends the request, it is in a simple arr ...

Sending information from JavaScript to Python scripts: best practices

Within this HTML file, I have included a script where an ajax request is being made to pass a specific string to a Python function. var message = "hello there!!!" $.ajax({ url: "../SCRIPTS/cond.py", type: 'POST', ...

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Restriction on Google Maps API: Mouseover functionality is limited to specific hours of the day

Throughout my programming journey, I've encountered some weird errors, but this one takes the cake. I'm stumped as to why it's happening. Here's the situation: My application is supposed to fetch data from a MySQL Database and display ...

Categorize a collection of objects based on shared characteristics

I am in need of the count for the current week only. Specifically, I want to calculate monthly totals with a breakdown per week. Currently, I can retrieve the weekly count for each month. Now, my goal is to display only the existing weeks. For example, if ...

What are the top recommendations for incorporating SVG inline within NuxtJS?

I have discovered a fantastic package that allows me to use SVG inline in NuxtJS and render it as HTML. The package I recommend is svg-inline-loader. This package enables the display of SVG as HTML, but it's important to note that all SVG elements mus ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

Unlock the potential of vue-datepicker by harnessing the power of multiple calendars

Currently, I am implementing the Composition API and utilizing the Vuepic/vue-datepicker library. However, I have encountered an issue with my datepicker setup. The code for my datepicker is as follows: <Datepicker multi-calendars multi-calendars-so ...