In Vue, how to cancel a checkbox based on a condition?
You should use v-model
instead of :checked
so that changes to the userOutputSeries
data property will be reflected in the checkbox input.
Then, pass the s
reference from the v-for
to the method and set that object's active
property to true
if there are no active
checkboxes:
new Vue({ el: '#app', data() { return { userOutputSeries: { foo: { display: 'Awesome Foo', active: true }, bar: { display: 'My Bar', active: false } } } }, methods: { preventIfLessThanOneChecked(item) { if (item.active) { return; } let items = Object.values(this.userOutputSeries); if (!items.find(i => i.active)) { item.active = true; } } }})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script><div id="app"> <div class="wrapper" v-for="(s, id) in userOutputSeries" :key="id"> <input type="checkbox" :id="id" :value="id" @change="preventIfLessThanOneChecked(s)" v-model="s.active"> <label :for="id">{{ s.display }}</label> </div></div>
Try using disabled
on your single checked checkbox:
<div class="wrapper" v-for="(s, id) in userOutputSeries" :key="id"> <input type="checkbox" :id="id" :value="id" :disabled="(s.active && numberOfChecked == 1) ? disabled : null" @change="preventIfLessThanOneChecked" :checked="s.active"> <label :for="id">{{ s.display }}</label></div>
In the above answer given by @thanksd, my checkbox remains unchecked.So i am writing my solution.
This my loop statement, change the variable names according to your file.
v-for="column in tableColumns"
This is my input ( if visible is true then checkbox is checked )
<input type="checkbox" v-model="column.visible" @change="event => visibleColumnsChanged(column, event)">
Then in my change method - if there is no visible item left set the column.visible to true - use event.target.checked = true to check the checkbox again.
visibleColumnsChanged: function(column, event){ if (column.visible) { return; } if(! this.tableColumns.find(c => c.visible)){ column.visible = true; event.target.checked = true; }}