Dynamic Value Checkbox Vuejs 2 Dynamic Value Checkbox Vuejs 2 vue.js vue.js

Dynamic Value Checkbox Vuejs 2


<div id="demo" >  <ul>    <li v-for="mainCat in mainCategories">      <input type="checkbox" :value="mainCat.merchantId" :id="mainCat.merchantId" v-model="checkedCategories" @click="check($event)"> {{mainCat.merchantId}}    </li>  </ul>  {{ checkedCategories }}</div>

And in your script:

var demo = new Vue({  el: '#demo',  data: {    checkedCategories: [],    mainCategories: [{        merchantId: '1'      }, {        merchantId: '2'      }]   },  methods: {    check: function(e) {      if (e.target.checked) {        console.log(e.target.value)      }    }  }})

Check this: https://vuejs.org/v2/guide/forms.html#Checkbox

Working fiddle: http://jsfiddle.net/yMv7y/9206/


new Vue({el: '#app',data() {return {mainCategory: {merchantIds: []},mainCategories: [{merchantId: 1,category: 'first category'},{merchantId: 2,category: 'second category'}]}},methods: {      merchantCategoryId: function() {    console.log(this.mainCategory.merchantIds)  }}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app"><li v-for="mainCat in mainCategories">  <input type="checkbox"   :value="mainCat.merchantId"   v-model="mainCategory.merchantIds"   id="mainCat.merchantId"   @click="merchantCategoryId"></li></div>

      OR

new Vue({el: '#app',data() {return {mainCategories: [{merchantId: 1,category: 'first category'},{merchantId: 2,category: 'second category'}]}},methods: {      merchantCategoryId: function(event) {    console.log(event.target.value, event.target.checked)  }}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="app"><li v-for="mainCat in mainCategories">  <input type="checkbox"   :value="mainCat.merchantId"  id="mainCat.merchantId"   @change="merchantCategoryId($event)"></li></div>

1.I observed both the mainCategories and v-model value v-model="mainCategories.merchantId" are the same.You cannot access the marchantId of mainCategories, this is the mistake what you did apart from that nothing is wrong in the code sample to get the value of marchantId.

2 When your using $event in the click or change event function no need to use the v-model value.