1

I have a function that pushes the networkAudience to the array when the checkbox is checked but when I unchecked it the same network Audience get pushed into the array again. Clicking the networkAudience should be removed when I uncheck the box.

How should I change my function so that a networkAudience is removed if it's 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>

This should only show one object because I unchecked a box but I end up with two objects. The unchecked box duplicates.

enter image description here

1 Answer 1

1

If I understood you correctly , try like following snippet:

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.