[Vuejs]-VueJS: Getting dynamic checkbox values in VueJS 2

0👍

First, try to add an empty selected array to each object inside preferences array:

preferences: [{
      id: "1",
      title: "Subscription frequence",
      options: ["Daily", "Weekly", "Fortnight", "Monthly"],
      selected: []
   },
   {
      id: "2",
      title: "Topics",
      options: ["Sports", "Politics", "Art", "Music", "Health", "Tech"],
      selected: []
   },
   {
      id: "3",
      title: "Promotional Offers",
      options: ["Daily", "Weekly", "Fortnight", "Monthly", "Never"],
      selected: []
   }
]

Next, in the template update the v-checkbox model from:

:v-model="pref.options"

to

:v-model="pref.selected"

Now, you can easily see the selected options in each preference like:

  • For Subscription frequence:
    • this.preferences[0].selected
  • For Topics:
    • this.preferences[1].selected
  • For Promotional Offers:
    • this.preferences[2].selected

Simple Demo:

new Vue({
  el: '#app',
  data: {
    selected: [],
    roles: [{id:1,name:"Client"},{id:2,name:"Admin"},{id:3,name:"Guest"}]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div v-for="role in roles" :key="role.id">
    <label>{{role.name}}</label>
    <input type="checkbox" v-model="selected" :value="role"/>
  </div>
  
  <p>Selected Roles:</p>
  {{selected}}
</div>

Complex Demo:

new Vue({
   el: '#app',
   data: {
      preferences: [{
            id: "1",
            title: "Subscription frequence",
            options: ["Daily", "Weekly", "Fortnight", "Monthly"],
            selected: []
         },
         {
            id: "2",
            title: "Topics",
            options: ["Sports", "Politics", "Art", "Music", "Health", "Tech"],
            selected: []
         }
      ]
   }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
   <div v-for="pref in preferences" :key="pref.id">
      <h3>{{pref.title}}:</h3>
      <div v-for="option in pref.options" :key="option">
         <label>{{option}}</label>
         <input type="checkbox" v-model="pref.selected" :value="option" /><br>
      </div>
      <p>Selected {{pref.title}}:</p>
      {{pref.selected}}
      <br><br><hr/>
   </div>
</div>

0👍

Add a selectedOption key in preferences objects.

preferences: [
{
  id: "1",
  title: "Subscription frequence",
  options: ["Daily", "Weekly", "Fortnight", "Monthly"],
  selectedOption: []
},
{
  id: "2",
  title: "Topics",
  options: ["Sports", "Politics", "Art", "Music", "Health", "Tech"],
  selectedOption: []
},
{
  id: "3",
  title: "Promotional Offers",
  options: ["Daily", "Weekly", "Fortnight", "Monthly", "Never"],
  selectedOption: []
}

]

<v-checkbox
v-for="option in pref.options"
:key="option"
:v-model="pref.selectedOption"
:label="option"
color="red"
value="option"
hide-details

>

Leave a comment