Home > Software design >  Set checkbox selected in Vue
Set checkbox selected in Vue

Time:02-16

I am beginner in vue and web developing. I make my app with Laravel and Vue.

I have this code:

created: function () {
let self = this;
self.setActive('tab1');
axios.get(this.$apiAdress   '/api/tasks/create?token='   localStorage.getItem("api_token"))
.then(function (response) {
self.documentDircionary = response.data.documentDircionary;
self.selectedDocumentDircionary = response.data.selectedDocumentDircionary;
}).catch(function (error) {
console.log(error);
self.$router.push({path: '/login'});
});
<template v-for="(option) in documentDircionary">
   <div  :key="option.name">
      <CCol sm="12">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" /> {{ option.label }}
      </CCol>
   </div>
</template>

This code show me inputs - and it's work fine. I have problem with set selected attribute for selected checkbox.

In array selectedDocumentDircionary results from api:

"selectedProducts": [1,2,43]

How can I set checked for only this checkbox, witch selectedProducts?

Please help me

CodePudding user response:

You can use :checked attribute to marked the checkbox checked as per the selectedProducts you have.

Working Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
        selectedProducts: [1, 2, 43],
      documentDircionary: [{
        name: 'checkbox1',
        value: 1,
        label: 'Checkbox 1'
      }, {
        name: 'checkbox2',
        value: 2,
        label: 'Checkbox 2'
      }, {
        name: 'checkbox3',
        value: 3,
        label: 'Checkbox 3'
      }, {
        name: 'checkbox4',
        value: 4,
        label: 'Checkbox 4'
      }, {
        name: 'checkbox43',
        value: 43,
        label: 'Checkbox 43'
      }]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>

<div id="app">
<template v-for="option in documentDircionary">
   <div :key="option.name">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" :checked="selectedProducts.includes(option.value)" /> {{ option.label }}
   </div>
</template>
</div>

CodePudding user response:

You can set :checked based on if the id of the current element is in the array:

<template v-for="(option) in documentDircionary">
   <div  :key="option.name">
      <CCol sm="12">
         <input type="checkbox" name="selectedDocuments[]" :id="option.value" :checked="selectedProducts.includes(option.value)" /> {{ option.label }}
      </CCol>
   </div>
</template>
  • Related