0

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 class="form-group form-row" :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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.