I wanted to get the checkboxes values and store it in an array using v-model, the first instance I toggle a check it doesn't register but when I check a second one and hit submit the second value registers, another problem is that when I try to select multiple checkboxes it only logs the recently checked box after triggering the handleClick function. I've also tried console logging filter.filtProv and it only logs the recently checked.
//vue app
var filter = {
filtProv: reactive([]) as String[]
}
var temp: any = []
let handleClick = () =>{
temp.push(filter.filtProv)
console.log(temp)
}
//template
<div id="checkboxes" v-for="provider in providerList" v-bind:key="provider" class="m-2">
<input class="mx-1" type="checkbox" :value="provider" v-model="filter.filtProv"/>
<label>{{provider}}</label>
</div>
You can achieve it by adding a checked parameter in your providerList objects.
For example :
{
value: string,
checked: boolean
}
And then at the end on submit you can filtered out the checked objects from the array.
Working Demo :
new Vue({
el: '#app',
data: {
providerList: [{
value: 'first checkbox',
checked: false
}, {
value: 'Second checkbox',
checked: false
}, {
value: 'Third checkbox',
checked: false
}, {
value: 'Fourth checkbox',
checked: false
}]
},
methods: {
submitForm() {
const result = this.providerList.filter((obj) => obj.checked).map((obj) => obj.value);
console.log(result);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div id="checkboxes" v-for="(provider, index) in providerList" v-bind:key="index" class="m-2">
<input class="mx-1" type="checkbox" :value="provider.value" v-model="provider.checked"/>
<label>{{provider.value}}</label>
</div><br>
<button @click="submitForm()">Submit!</button>
</div>