0

Am very new to vue js and need a way where I have multiple checkboxes and when I select them an array gets updated with the checked elements with Vue JS. Eg :

allcolors = ['Red', 'Blue', 'Green']; and I select first two so my

selectedColors = ['Red', 'Blue']; and then click saves, saves it to database.

When I open the form Red and Blue gets checked fetching record from database.

fetchedColors = ['Red', 'Blue'];

2 Answers 2

1

new Vue({
  el: "#app",
  data: {
    items: [
      { label: 'Red', value: 'red' },
      { label: 'Blue', value: 'blue' },
      { label: 'Green', value: 'green' },
    ],
    checkedValues: [],
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <label 
    v-for="(item, index) in items"
    :key="index"
   >
    {{ item.label }}
    <input 
     type="checkbox"
     :value="item.value"
     v-model="checkedValues"
    />
  </label>
  {{ checkedValues }}
</div>

Not really sure what you're asking. Do you mean something like this? Check the docs they may help - https://v2.vuejs.org/v2/guide/forms.html#Checkbox

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

1 Comment

I want to display selected checkboxes on display of form.
1

new Vue({
  el: "#app",
  data: {
    items: [
      { label: 'Red', checked: true },
      { label: 'Blue', checked: true },
      { label: 'Green', checked: false },
    ],
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <label 
    v-for="(item, index) in items"
    :key="index"
   >
    {{ item.label }}
    <input 
     type="checkbox"
     :checked="item.checked"
     @change="({ target: { checked }}) => items[index].checked = checked"
    />
  </label>
</div>

If you want to show checkboxes that are checked when the form displays you could do something like this.

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.