Andath
Andath

Reputation: 22724

Vuetify: checkbox shows status is checked when it is unchecked, and vice versa

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?

Codepen demo

Upvotes: 3

Views: 7539

Answers (1)

Hammerbot
Hammerbot

Reputation: 16344

the console.log you get is triggered before the action of checking or unchecking the checkbox. So this is what happen:

  1. The user clicks on the checkbox
  2. The Javascript executes the listener
  3. If the event is not canceled in any of the listener, it continues and sets the checkbox as checked or unchecked.

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

Related Questions