yrbet
yrbet

Reputation: 191

Passing checkbox true or false VueJS

I have a checkbox on my VueJS site, I want to do the following: if the checkbox special is true, then send in database value 1 in column, how can I do this correctly?

I did like this:

<label class="checkbox-control">
  <input type="checkbox" v-model="special"  v-on:change="special"  :disabled="channel.length === 0">

  <div class="checkbox-control__content"><i></i>Test</div>
</label>

data() {
    return {
      channel: "",
      special: false,
    }
    sendFunction() {
      this.$root.axios.post("/user/userPromo", {
        channel: this.channel,
        special: this.special
      }).then((res) => {
        const data = res.data;
        this.$root.showNotify(data.type, this.$t(`index.${data.message}`, {
          name: data.name
        }));
      });
    },

And in backend when i add data in table, i use $special = $r->get('special');, but it doesn't want to work. When is my mistake?

Upvotes: 3

Views: 11621

Answers (1)

ikiK
ikiK

Reputation: 6532

You can use: true-value="1" false-value="false"

<input type="checkbox" v-model="toggle" true-value="1" false-value="false" />

// when checked:
vm.toggle === '1'
// when unchecked:
vm.toggle === 'false'

Vue2 and Vue3 :

https://v3.vuejs.org/guide/forms.html#checkbox-2

https://v2.vuejs.org/v2/guide/forms.html#Checkbox

Then use this.special inside methods sendFunction:

var app = new Vue({
  el: '#app',
  data: {
    special: false
  },
  methods: {
    sendFunction: function(event) {
    
      console.log(this.special)
      
      //this.$root.axios.post("/user/userPromo", {
        //channel: this.channel,
        //special: this.special
      //}).then((res) => {
        //const data = res.data;
        //this.$root.showNotify(data.type, this.$t(`index.${data.message}`, {
          //name: data.name
        //}));
      //});
    }  
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <input type="checkbox" v-model="special" v-on:change="sendFunction" true-value="1" false-value="false">
</div>

Also if if this.special wont be available inside axios it means this will be bound to axios function so you need to save data before and use it inside as saved variable:

 sendFunction: function(event) {
        const value = this.special      
          this.$root.axios.post("/user/userPromo", {
          //use value here

Upvotes: 8

Related Questions