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
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With