wbdlc
wbdlc

Reputation: 1089

How Can I Make All Checkboxes "Checked" By Default

How can I ensure by default all by checkboxes (output from my data) are all checked by default on load?

Output checkbox

<div v-for="(category, index) in remove_category_duplicates" class="form-check">
    <input type="checkbox" class="form-check-input" v-model="cat_data" :id="category" :value="category">
    <label class="form-check-label">{{ category }}</label>
</div>

Setup checkbox values from data

    remove_category_duplicates: function () {
        // Get all categories and remove duplicates
        let data = {}
        this.info.forEach(i=>{
            Object.assign(data,i.category_data);
        })

        return data;
    },

Data:

{
    "id": 1,
    "title": "Title one",
    "category_data": {
        "2": "Team",
        "7": "Queries"
    }
},

CodePen: https://codepen.io/anon/pen/XxNORW?editors=1011

Thanks

Upvotes: 0

Views: 870

Answers (1)

tony19
tony19

Reputation: 138226

To initialize the checkboxes to true/checked, their v-model array (cat_data) should contain the true-value of each checkbox. In this case, it would be:

["Team", "Questions", "Queries", "Fax"]

Here's how I would update your code:

  1. Add a computed property to return an array of available categories:

    computed: {
      categories() {
        const cats = this.remove_category_duplicates;
        return Object.keys(cats).map(k => cats[k]);
      }
    }
    
  2. Update select() to set cat_data based on selectAll. If selectAll is true, set cat_data to the category array computed above (thus marking all boxes checked), or else an empty array (thus unchecking all boxes):

    methods: {
      select() {
        this.cat_data = this.selectAll ? this.categories : [];
      }
    }
    
  3. Add a method (e.g., named "toggleSelectAll") to toggle selectAll based on whether all checkboxes are checked, keeping the Select All checkbox in sync with the state of the other checkboxes:

    methods: {
      toggleSelectAll(e) {
        const checked = e.currentTarget.checked;
        if (checked) {
          this.selectAll = this.arrayContains(this.categories, this.cat_data);
        } else {
          this.selectAll = false;
        }
      }
    }
    
  4. Add a change-handler on each checkbox (except the Select All box) that calls toggleSelectAll defined above:

    <div v-for="category in remove_category_duplicates">
      <input type="checkbox" @change="toggleSelectAll">
    

demo

Upvotes: 1

Related Questions