Reputation: 22724
Let me simplify the issue:
I have a checkbox in my Vue.js template (using Vuetify components):
<v-checkbox
v-model="selected"
label="John"
value="John"
id ="john"
@click.native="checkit">
</v-checkbox>
The checkit()
method code is:
checkit: function() {
let elt = document.getElementById('john')
if(elt.checked) {
console.log('checked')
} else {
console.log('unchecked')
}
}
But I am getting the opposite result: when it is checked it says it is unchecked and vice versa.
What causes this and how to fix it?
Upvotes: 3
Views: 7539
Reputation: 16344
the console.log you get is triggered before the action of checking or unchecking the checkbox. So this is what happen:
What you could use is listen on the change
event: https://codepen.io/anon/pen/VGOMPB?editors=1011
The second thing is that, by using document.getElementById('john')
you are relying on the DOM here to check if the checkbox is checked or not. Why don't you rely on the selected
property? DOM is updated after all the JS has been executed in order to avoid refreshing the DOM too frequently. If you want to wait the DOM to be updated, you can use the $nextTick
helper: https://codepen.io/anon/pen/BOewpg?editors=1011
checkit: function () {
this.$nextTick(() => {
let elt = document.getElementById('john')
if(elt.checked) {
console.log('checked')
} else {
console.log('unchecked')
}
})
//this.selected.push('Vuejs')
//this.selected.push('Paris')
}
Upvotes: 9