Vue Js Checkbox Select all | Unselect All | Checked | Unchecked All . This code snippet demonstrates how to implement a select/unselect all feature for checkboxes in Vue.js using two-way bindings. When the user clicks the “Select All” checkbox, all the checkboxes on the page will be selected, and when the user clicks “Unselect All,” all the checkboxes will be unchecked. Additionally, if any of the individual checkboxes are checked or unchecked, the “Select All” checkbox will update accordingly. This is achieved by using a computed property to determine the state of the “Select All” checkbox, and then binding this property to both the “Select All” checkbox and the individual checkboxes. Overall, the code is concise and easy to understand, making it a great starting point for anyone looking to implement this feature in their own Vue.js application.
Vue JS Checkbox Select/Unselect all Example
This code is written in JavaScript using the Vue.js framework. It creates a Vue app that has a data property containing an array of countries, each represented by an object with an id and countryName. It also has a checked array that will hold the names of the countries that are checked.
The app also has a computed property called checkAll that gets and sets the checked property based on whether all countries are checked or not. The get function returns true if the number of checked countries is equal to the total number of countries in the country array, otherwise it returns false. The set function sets the checked property based on whether the value passed in is true or false. If it’s true, all countries are added to the checked array, otherwise the checked array is emptied.
<div id='app'>
<div class="form-check">
<input class="form-check-input" type='checkbox' id='selectAll' v-model='checkAll' />
<label class="form-check-label" for='selectAll'>Select all</label>
</div>
<div class="form-check form-check-inline" v-for='c in country'>
<input class="form-check-input" type='checkbox' :id='c.id' v-model='checked' :value="c.countryName" />
<label class="form-check-label" :for='c.id' >{{c.countryName}}</label>
</div>
<p>{{checked}}</p>
</div>
<script type="module">
import { createApp } from 'vue'
createApp({
data() {
return {
country:[
{
'id':'1',
'countryName':'AMERICA'
},
{
'id':'2',
'countryName':'AUSTRALIA'
},
{
'id':'3',
'countryName':'INDIA'
},
{
'id':'4',
'countryName':'ENGLAND'
}
],
checked:[]
}
},
computed: {
checkAll: {
get: function () {
return this.country ? this.checked.length == this.country.length : false;
},
set: function (value) {
var checked = [];
if (value) {
this.country.forEach(function (c) {
checked.push(c.countryName);
});
}
this.checked = checked;
}
}
}
}).mount('#app')
</script>