0

When using v-for, I need to allocate a number of materials with a checkbox. But when you click on the checkbox, a group of materials is immediately highlighted. This is due to the fact that the Quantity parameter is the same for many materials. How do I make sure that when I click on the checkbox, only one material is highlighted and the Quantity value is added to checkedMaterials?enter image description here

 <table>
            <thead>
            <tr>
                <th>#</th>
                <th>Material name</th>
                <th>Количество</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="material in materials">
                    <td><input type="checkbox" :value="material" v-model="checkedMaterials">
                        {{material.id}}
                    </td>{{ material.name }}</td>
                    <td>{{ material.Quantity }}</td>
                </tr>
export default {
name: "Show",

data() {
    return {
        materials: '',
        checkedMaterials: [],
    }
},

mounted() {
    this.getPart()
    this.getMaterials()
},

methods: {
    getPart() {
        axios.get(`/api/part/${this.$route.params.id}`).then(res => {
            this.part = res.data.data
        })
    },

    getMaterials() {
        axios.get('/api/material').then(res => {
            this.materials = res.data.data;
            })
       },
  },

}

1
  • Your code should work perfectly. I did not see any issue in that. Here, I created a demo fiddle for the reference : jsfiddle.net/hcd1o4f7 Commented Sep 5, 2022 at 12:13

1 Answer 1

1
  1. take id as value instead of whole material.

              <tr v-for="material in materials">
                   <td><input type="checkbox" :value="material.id" v-model="checkedMaterials">
                       {{material.id}}
                   </td>{{ material.name }}</td>
                   <td>{{ material.Quantity }}</td>
               </tr>
    
  2. make computed propery for getting quantity .

     computed : {
    
         allSelectedMaterial() {
             return this.materials.filter((material) => 
                     this.checkedMaterials.includes(material.id) )
         },
         selectedMaterialQuantitry(){
              return this.allSelectedMaterial.map((material) => material.quantity)
         },
         uniqueSelectedQuantity(){
           return [...new Set(this.selectedMaterialQuantitry)]
         }
      },
    

code : https://jsfiddle.net/d9nwz4kt/35/

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

2 Comments

meet vaghsiya, rhank you very much!!!!
It's my pleasure!!

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.