I am trying to uncheck a checkbox which is checked using its label in VueJs.
DEMO:
new Vue({
el: '#app',
data: {
checkedNames: [],
checkedName: true
},
methods: {
uncheck: function() {
this.checkedName = !this.checkedName;
}
}
})
li.badge.badge-primary {
cursor: pointer;
margin: 5px;
font-size: 100%;
}
ul.checkboxes {
list-style: none;
}
ul.tags {
margin-top: -110px;
margin-left: 85px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id='app'>
<ul class="checkboxes">
<li><input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label></li>
<li><input type="checkbox" id="john" value="John" v-model="checkedNames">
<label for="john">John</label></li>
<li><input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label></li>
</ul>
<br/>
<ul class="tags">
<li @click="uncheck" class="badge badge-pill badge-primary" v-for="checkedName in checkedNames">
{{ checkedName }}
</li>
</ul>
</div>
Here I am not able to uncheck the selected checkbox using it label as show in my above code.
Just started with VueJS, help appreciated.
Pass the checkedName
as argument to the method and filter the array instead of assigning a variable.
First, add checkedName
argument to uncheck
:
<li @click="uncheck(checkedName)" ... v-for="checkedName in checkedNames">
And then use that argument to remove that name from the checkedNames
array:
this.checkedNames = this.checkedNames.filter(name => name !== checkedName);
Demo below.
new Vue({
el: '#app',
data: {
checkedNames: [],
checkedName: true
},
methods: {
uncheck: function(checkedName) {
this.checkedNames = this.checkedNames.filter(name => name !== checkedName);
//this.checkedName = !this.checkedName;
}
}
})
li.badge.badge-primary {
cursor: pointer;
margin: 5px;
font-size: 100%;
}
ul.checkboxes {
list-style: none;
}
ul.tags {
margin-top: -110px;
margin-left: 85px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id='app'>
<ul class="checkboxes">
<li><input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label></li>
<li><input type="checkbox" id="john" value="John" v-model="checkedNames">
<label for="john">John</label></li>
<li><input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label></li>
</ul>
<br/>
<ul class="tags">
<li @click="uncheck(checkedName)" class="badge badge-pill badge-primary" v-for="checkedName in checkedNames">
{{ checkedName }}
</li>
</ul>
</div>
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