[Vuejs]-Multiple checkboxes using v-for vue ts

0👍

You can achieve it by adding a checked parameter in your providerList objects.

For example :

{
  value: string,
  checked: boolean
}

And then at the end on submit you can filtered out the checked objects from the array.

Working Demo :

new Vue({
  el: '#app',
  data: {
    providerList: [{
        value: 'first checkbox',
      checked: false
    }, {
        value: 'Second checkbox',
      checked: false
    }, {
        value: 'Third checkbox',
      checked: false
    }, {
        value: 'Fourth checkbox',
      checked: false
    }]
  },
  methods: {
    submitForm() {
      const result = this.providerList.filter((obj) => obj.checked).map((obj) => obj.value);
      console.log(result);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div id="checkboxes" v-for="(provider, index) in providerList" v-bind:key="index" class="m-2">
    <input class="mx-1" type="checkbox" :value="provider.value" v-model="provider.checked"/>
    <label>{{provider.value}}</label>
  </div><br>
  <button @click="submitForm()">Submit!</button>
</div>

Leave a comment