How we can get the value of checkbox an input to an array?
Here is my code, I've tried this:
<cbComp
v-for="name in names"
v-bind:key="name"
v-model="selected_name[name]">
<span> {{ name }} </span>
</cbComp>
Name: {{ selected_name }}
data () {
return {
names: ['Michael', 'Millie', 'Brown'],
selected_name: []
}
},
This was the cbComp
template:
<template>
<label >
<input
:id="cb"
type="checkbox"
:value="modelValue"
v-model="computedValue"
>
<label
:for="cb">
<slot/>
</label>
</label>
</template>
This is the javascript:
export default {
data: {
updateValue: this.value
},
props: {
value: undefined,
modelValue: {
type: undefined,
default: false
}
},
computed: {
computedValue: {
get () {
return this.updateValue
},
set (value) {
this.updateValue = value
this.$emit('input', value)
}
}
},
watch: {
value (value) {
this.updateValue = value
}
}
}
It turns out there is no error, and the selected name won't appear on {{ selected_name }}
CodePudding user response:
You simply need to bind your v-model
to the selected_name
property. Here is a bare minimum example for you to work off of:
<html>
<div id="app">
<p>Names: {{ selected_name.join(', ') }}</p>
<label for="maxCheckbox">Max</label>
<input type="checkbox" value="Max" v-model="selected_name" id="maxCheckbox">
<label for="markCheckbox">Mark</label>
<input type="checkbox" value="Mark" v-model="selected_name" id="markCheckbox">
<label for="johnCheckbox">John</label>
<input type="checkbox" value="John" v-model="selected_name" id="johnCheckbox">
</div>
<script src="https://unpkg.com/vue@2"></script>
<script>
new Vue({
el: '#app',
data() {
return {
selected_name: []
}
}
});
</script>
</html>
As a side note, I would probably rename your selected_name
to be more clear like selected_names
or more commonly you'll find selectedNames
camelCase.