Home > database >  Issue when trying to select one checkbox inside v-for in Vuejs?
Issue when trying to select one checkbox inside v-for in Vuejs?

Time:12-03

<div id="example-1">
  <ul>
    <input type="text" v-model="searchString" placeholder="Filter" />
    <p>sortKey = {{sortKey}}</p>
    <li v-for="item in sortedItems">
      <input class="checkbox-align" type="checkbox" :value="item.name" id="productname" v-model="checked" /> {{ item.price }} - {{ item.name }}
    </li>
  </ul>
  <div class="cecont" v-if="!checked">
    <p>text content</p>
  </div>

</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Codepen link:- https://codepen.io/dhanunjayt/pen/oNGXjZL

With the above code in codepen, I am able to perfom task like, on clicking on checkbox the content should be hidden. Where i am able to achieve it. But problem is, on clicking of one checkbox, I am able to select multiple checkboxes.

So resolve this issue, Do i need to add id attribute to input??

or change my v-model attribute, and if i change my v-model to checked.name functionality not working.

How to solve this issue?

CodePudding user response:

You should set checked property to individual item

You are creating multiple checkboxes with all having the same v-model value, which is checked. If any one of the checkboxes is checked, all the checkboxes will be checked together.

Solution.

You should set the checked property to each item in the loop. This will make the v-model work independently.

var example1 = new Vue({
  el: '#example-1',
  data: {
    // sort: item,
    sortKey: 'name',
    checked: false,
    searchString: "",
    items: [
      { price: '1', name: 'mm', checked: false },
      { price: '22', name: 'aa', checked: false },
      { price: '55', name: 'dd', checked: false },
      { price: '77', name: 'gg', checked: false },
      { price: '123', name: 'kk', checked: false },
      { price: '53', name: 'mn', checked: false },
    ]
  },
  computed: {
    checkedLength() {
      return checkedLength = this.items.filter(item => item.checked === true).length;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<div id="example-1">
  <ul>
    <input type="text" v-model="searchString" placeholder="Filter" />
    <p>sortKey = {{sortKey}}</p>
    <li v-for="item in items">
      <input class="checkbox-align" type="checkbox" :value="item.name" id="productname" v-model="item.checked" /> {{ item.price }} - {{ item.name }}
    </li>
  </ul>
  <p> checkedLength {{checkedLength}}</p>
  <div class="cecont" v-if="checkedLength > 0">
    <p>text content</p>
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related