vuejs check checkbox if id is in array

Viewed 3317

Hey everyone I've been at this for over two weeks and still cant figure this out. I have two json encoded arrays.

categories:

[{"id":"1","category":"Holiday"},{"id":"2","category":"Sports"},{"id":"3","category":"Misc"},{"id":"4","category":"Automotive"},{"id":"6","category":"Retail"},{"id":"7","category":"Financial"},{"id":"8","category":"Church"},{"id":"9","category":"Community"},{"id":"10","category":"Food"},{"id":"11","category":"Healthcare"}]

selectedCategories:

[{"0":"3","id":"3"},{"0":"4","id":"4"}]

What I've been trying to do is write a vuejs method that checks the checkboxes if the id is in the currentlySelectedCategories array when it loads and places them in the currentlySelected array in the data property. However when I attempt to do this I am able to place them in the array but the checkboxes are not checked. In this case Misc and Automotive should be checked as id 3 and 4 are in selectedCategories

    <?php session_start(); ob_start(); require_once('database.php'); $templateId=$_GET['id']; require_once('header.php');

$currentlySelectedCategoriesQuery="SELECT id FROM dataclayCategories WHERE id IN (SELECT dataclayCategoryLink.categoryId FROM dataclayCategoryLink WHERE dataclayCategoryLink.templateId='$templateId')";
    $currentlySelectedCategoriesResult=mysqli_query($mysqli, $currentlySelectedCategoriesQuery);
    $currentlyAssociatedCategories=array();
    while($row=mysqli_fetch_array($currentlySelectedCategoriesResult)){
        $currentlyAssociatedCategories[]=$row;
    }

    $selectDataclayTemplatesCategories="SELECT * FROM creative_engine.dataclayCategories";
    $result = mysqli_query($mysqli, $selectDataclayTemplatesCategories);
    $categoryArray=array();
    while($row=mysqli_fetch_assoc($result)){
    $categoryArray[]=$row;
    }
    ?>
    <div id="app" >
        <div class="content container">
    <form role="form" onsubmit="return false">
      <div class="form-group">
    <label v-for="item in categories" class="checkbox-inline">
        <input type="checkbox" :value=item.id :id="item.id" v-model="selectedCategories" name="selectedCategories[]" @click="check($event)">{{item.category}}
          </label>
    </div>
    </form>
        </div>
        </div>

    <script>
      var app = new Vue({
      el: '#app',
      data: {
        selectedCategories: [],
        categories: []
      },
      created: function(){
      this.categories=<?php echo json_encode($categoryArray);?>;
      this.selectedCategories=<?php echo json_encode($currentlyAssociatedCategories);?>;
      },
      methods: {
        check: function(e) {
          if (e.target.checked) {
            console.log(e.target.value)
          }
        }
      }
    });
    </script>
1 Answers

I found a way to accomplish what you are looking for. I am using a computed property to return a modified version of the original array than includes a checked property for each object. Here is a working example, adjusted to exclude the PHP calls. https://codepen.io/anon/pen/eLjeYE

<template>
  <div id="app">
    <div class="content container">
      <form role="form" onsubmit="return false">
        <div class="form-group">
          <label v-for="(item, idx) in checkedCategories" class="checkbox-inline" v-bind:key="idx">
            <input type="checkbox" :value=item.id :id="item.id" :checked="item.checked" @click="check($event)">{{item.category}}
          </label>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      selectedCategories: [{"0":"3","id":"3"},{"0":"4","id":"4"}],
      categories: [{"id":"1","category":"Holiday"},{"id":"2","category":"Sports"},{"id":"3","category":"Misc"},{"id":"4","category":"Automotive"},{"id":"6","category":"Retail"},{"id":"7","category":"Financial"},{"id":"8","category":"Church"},{"id":"9","category":"Community"},{"id":"10","category":"Food"},{"id":"11","category":"Healthcare"}],
    }
  },
  computed: {
    checkedCategories: function () {
      var checkedIds = []
      var results = []
      for (var i = 0; i < this.selectedCategories.length; i++ ) {
        checkedIds.push(this.selectedCategories[i].id)
      }
      for (var j = 0; j < this.categories.length; j++ ) {
        var item = this.categories[j];
        if (checkedIds.includes(this.categories[j].id)) {
          item.checked = true
        } else {
          item.checked = false
        }
        results.push(item)
      }
      return results
    }
  },
  methods: {
    check (e) {
      if (e.target.checked) {
        var newCat = {
          '0': e.target.value,
          'id': e.target.value
        }
        this.selectedCategories.push(newCat)
      } else {
        for (var i = 0; i < this.selectedCategories.length; i++ ) {
          if (this.selectedCategories[i].id == e.target.value) {
            this.selectedCategories.splice(i, 1)
          }
        }
      }
    }
  }
}
</script>
Related