Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Value Checkbox Vuejs 2

I can't get the value of the checkbox.

    <li v-for="mainCat in mainCategories">
      <input type="checkbox" :value="mainCat.merchantId" v-model="mainCategories.merchantId" id="mainCat.merchantId" @click="merchantCategoryId">
    </li>

My Methods:

    methods: {    
      merchantCategoryId: function() {
        console.log(this.mainCategories.merchantId)
      }
    }

When it clicks I only get true and false for uncheck. TY

like image 611
Rbex Avatar asked May 05 '17 05:05

Rbex


2 Answers

<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/

like image 197
Deepak Avatar answered Sep 22 '22 07:09

Deepak


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.

like image 38
s srinivas Avatar answered Sep 23 '22 07:09

s srinivas