Skip to content
Advertisement

How to v-for checked value

I’m trying to create a checkbox select only one.

<div id="app">
 <div v-for="(question, index) in questions">
   <input type="checkbox" value="question.value" v-model="additional_grouped"  @change="uniqueCheck"> {{question.title}}
  </div>
  {{ result }}
</div>

My JS looks like the following:

new Vue({
  el: '#app',
  data() {
    return {
      additional: [],
      additional_grouped: [],
       questions: [
         {
           title: 'A',
           value: 0
         },
         {
           title: 'B',
           value: 1
         },
         {
           title: 'C',
           value: 2
         }
       ]
    }
  },
  computed: {
    result: function(){
      return this.additional.concat(this.additional_grouped);
    }
  },
  methods: {
    uniqueCheck(e){
      console.log(e)
      this.additional_grouped = [];
      if (e.target.checked) {
          this.additional_grouped.push(e.target.value);
      }
    }
  }
});

This is the old result.

enter image description here

I’m trying to get results like this.

enter image description here

I can do this by not the v-for method, but I want to do it this way. Because I have a lot of data, How can I checked value in v-for?

Here is my pen: enter link description here

Advertisement

Answer

You are missing the value binding (:value), here’s your example fixed:

new Vue({
  el: '#app',
  data() {
    return {
      additional: [],
      additional_grouped: [],
       questions: [
         {
           title: 'A',
           value: 0
         },
         {
           title: 'B',
           value: 1
         },
         {
           title: 'C',
           value: 2
         }
       ]
    }
  },
  computed: {
    result: function(){
      return this.additional.concat(this.additional_grouped);
    }
  },
  methods: {
    uniqueCheck(e){
      this.additional_grouped = [];
      if (e.target.checked) {
          this.additional_grouped.push(e.target.value);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 <div v-for="(question, index) in questions">
   <input type="checkbox" :value="question.value" v-model="additional_grouped"  @change="uniqueCheck"> {{question.title}}
  </div>
  {{ result }}
</div>

Documentation

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement