I’m trying to create a checkbox select only one.
JavaScript
x
7
1
<div id="app">
2
<div v-for="(question, index) in questions">
3
<input type="checkbox" value="question.value" v-model="additional_grouped" @change="uniqueCheck"> {{question.title}}
4
</div>
5
{{ result }}
6
</div>
7
My JS looks like the following:
JavaScript
1
38
38
1
new Vue({
2
el: '#app',
3
data() {
4
return {
5
additional: [],
6
additional_grouped: [],
7
questions: [
8
{
9
title: 'A',
10
value: 0
11
},
12
{
13
title: 'B',
14
value: 1
15
},
16
{
17
title: 'C',
18
value: 2
19
}
20
]
21
}
22
},
23
computed: {
24
result: function(){
25
return this.additional.concat(this.additional_grouped);
26
}
27
},
28
methods: {
29
uniqueCheck(e){
30
console.log(e)
31
this.additional_grouped = [];
32
if (e.target.checked) {
33
this.additional_grouped.push(e.target.value);
34
}
35
}
36
}
37
});
38
This is the old result.
I’m trying to get results like this.
I can do this by not the v-for method, but I want to do it this way. Because I have a lot of data, How can I checked value in v-for?
Here is my pen: enter link description here
Advertisement
Answer
You are missing the value binding (:value
), here’s your example fixed:
JavaScript
1
36
36
1
new Vue({
2
el: '#app',
3
data() {
4
return {
5
additional: [],
6
additional_grouped: [],
7
questions: [
8
{
9
title: 'A',
10
value: 0
11
},
12
{
13
title: 'B',
14
value: 1
15
},
16
{
17
title: 'C',
18
value: 2
19
}
20
]
21
}
22
},
23
computed: {
24
result: function(){
25
return this.additional.concat(this.additional_grouped);
26
}
27
},
28
methods: {
29
uniqueCheck(e){
30
this.additional_grouped = [];
31
if (e.target.checked) {
32
this.additional_grouped.push(e.target.value);
33
}
34
}
35
}
36
});
JavaScript
1
7
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
2
<div id="app">
3
<div v-for="(question, index) in questions">
4
<input type="checkbox" :value="question.value" v-model="additional_grouped" @change="uniqueCheck"> {{question.title}}
5
</div>
6
{{ result }}
7
</div>